Conversion of unsigned int to hex string without use of sprintf

Viewed 703

I am trying to implement the following (without sprintf or formatting):

    void integer_to_string(unsigned int a, char *string)
{
    char arr[16] = "0123456789abcdef";
    char *p = (char *)&a;
    unsigned int i;

    for (i = 0; i < 4; i++) {
        unsigned char lo = p[i] & 0xf; 
        unsigned char hi = p[i] >> 4;

        string[i*2] = arr[hi];
        string[i*2+1] = arr[lo];
    }
    string[2*i] = '\0';
}

This program is converting from an integer a and converting a into hexadecimal and saving the rest as a string. So, it is supposed to return an int like 10 to "0000000a" but instead is giving me a value of "0a000000" instead. What am I doing wrong? How do I move the 0a to the end instead of the beginning.

1 Answers

Accessing the correct significant bytes via char *p = (char *)&a; is endian dependent and in OP's case, the wrong order.


Get the order right and avoid endian-ness issues by using math, not casts:

for (i = 0; i < 8; i++) {
    unsigned char ch = (a >> ((32-4) - i*4)) & 0xF; 
    string[i] = arr[ch];
}
string[i] = '\0';

Simplification exist.

Related