Question:
Convert unsigned int to char * in C++?
1970-01-01 00:00:00 UTC
Convert unsigned int to char * in C++?
Five answers:
Samwise
2010-02-19 09:48:20 UTC
You haven't described what the value means as an unsigned int, or what the returned char * would mean, or the relationship between them. There are lots of ways to perform "conversions" that produce nonsense results.



If the value is, in fact, the character value to be returned, then you could allocate character space for it, store the value as a character in that space, and return a pointer to it.



If it's an index to the character to be returned, on the other hand, all you have to do is convert it to a pointer and return that. For example, suppose

indx is the unsigned integer index of a character in

ch_array, an array of characters.



Then you could simply return the value ch_array+indx, which would be a pointer to the indexed character in the array.
harrelson
2016-10-21 10:31:00 UTC
int i; char *c = (char*)&i; The order of the bytes is particular to the CPU sort. Intel x86 shop the least considerable byte first. it is termed little-endian. the choice is gigantic-endian.
Revenant
2010-02-19 09:55:10 UTC
Without itoa:



int number = 10;



stringstream ss;

ss << number;



cout << ss.str() << endl;
2010-02-19 09:51:17 UTC
Do you mean convert 3 to "3"? itoa() If you want to do it without using itoa(), if it's between 0 and 9, add 48 to it. If not, break it down to individual digits, then convert each one (by adding 48 to it).



Or do you mean convert 65 to "A"? (It already is.)
cja
2010-02-19 10:06:12 UTC
I'm assuming you want to write your own itoa function. See below for one way to do it. Normally I don't like functions allocating memory for the caller, but in this case it's either that, or trust the caller to provide a pointer to an array of sufficient size. Anyway, here's something that should give you some ideas for how to write your program:



#include



using namespace std;



char *myItoA(const unsigned);

size_t numDigits(const unsigned);

unsigned rev(unsigned);



int main(int argc, char *argv[]) {

    char *s1, *s2;



    s1 = myItoA(1024);

    s2 = myItoA(0);

    cout << s1 << endl;

    cout << s2 << endl;



    delete s1;

    delete s2;



    return 0;

}



char *myItoA(const unsigned i) {

    size_t n = numDigits(i);

    char *s = new char[n+1];

    unsigned x = rev(i);



    for (size_t j = 0; j < n; j++, x /= 10) {

        s[j] = (x % 10) + '0';

    }

   

    return s;

}



size_t numDigits(const unsigned n) {

    if (n < 10) return 1;

    return 1 + numDigits(n / 10);

}



unsigned rev(unsigned n) {

    int r = 0;



    do {

        r = (r * 10) + (n % 10);

    } while ((n /= 10) > 0);



    return r;

}



#if 0



Program output:



1024

0



#endif


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...