0

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;
}
IronMage
  • 41
  • 7
  • You *can't* set a variable with type `uint32_t` to the string. C has "strong typing" meaning you can't loosely convert one type to another. You converted a binary value to a string. If you want it as a binary value you'll have to convert it back. But you could have converted the `uint32_t` to a hexadecimal string like this: `sprintf(hold, "%lX", conversion)` although `hold[8]` won't be big enough to hold the 0 terminator that C strings have. – Weather Vane May 20 '15 at 17:45
  • 1
    BTW there is no such thing as a `base-10 unsigned int`. They are just binary bits. The difference between decimal, binary, hex, octal is just the human decision as to how they are represented in string format (apart from BCD representation, which isn't used in high level langages). – Weather Vane May 20 '15 at 17:50

1 Answers1

4

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
user4520
  • 3,401
  • 1
  • 27
  • 50
  • My problem isn't the conversion of int -> char[], it's that I need to be able to set a uint32_t equal to that char[]. – IronMage May 20 '15 at 17:44
  • @IronMage You cannot set `uint32_t` to be equal to a "string". In fact there's no such thing as a `string` in C, you only have `char*`. You will _need_ to convert the string representation of a number back to bits to be able to assign it to an `uint32_t`. – user4520 May 20 '15 at 17:47
  • How would I convert the string into a form that I can assign to a uint32_t ? – IronMage May 20 '15 at 17:52