IronMage
IronMage

Reputation: 41

Converting a character array to be handled as a hex in C

I've just recently been required to work with C—I normally work with Python and a bit of Java—and I've been running into some issues.

I created a function that converts a base-10 unsigned int into a character array that represents the equivalent hex. Now I need to be able to set a variable with type uint32_t to this 'hex'; what can I do to make sure this char[] is treated as an actual hex value?

The code is below:

int DecToHex(long int conversion, char * regParams[])
{    
    int hold[8];

    for (int index = 0; conversion > 0; index++)
    {
        hold[index] = conversion % 16;
        conversion = conversion / 16;
    }

    int j = 0;

    for (int i = 7; i > -1; i--)
    {
        if (hold[i] < 10 && hold[i] >= 0)
        {
            regParams[j] = '0' + hold[i];
        }
        else if (hold[i] > 9 && hold[i] < 16)
        {
            regParams[j] = '7' + hold[i];
        }
        else
        {
            j--;
        }
        j++;
    }
    return 0;
}

Upvotes: 0

Views: 1475

Answers (1)

user4520
user4520

Reputation: 3457

You should just use snprintf:

int x = 0xDA8F;
char buf[9];
snprintf(buf, sizeof(buf), "%X", x);   // Use %x for lowercase hex digits

To convert a hex representation of a number to an int, use strtol (the third argument to it lets you specify the base), or, since you want to assign it to an unsigned data type, strtoul.

The code would look something like this:

char* HexStr = "8ADF4B";
uint32_t Num = strtoul(HexStr, NULL, 16);
printf("%X\n", Num);        // Outputs 8ADF4B

Upvotes: 4

Related Questions