bvpx
bvpx

Reputation: 1297

C: converting a uint8 array to a string containing the hex representation of its bytes

I have a uint8 array:

int i = 0;
uint8_t x[32];

for (i = 0; i < 32; i++) {
    x[i] = i*i;
    printf("x[%d]: %02X\n", i, x[i]);
}

Here are the contents of the array:

x[0]: 0 00
x[1]: 1 01
x[2]: 4 04
...
x[14]: 196 C4
x[15]: 225 E1
...etc

I want to convert the x array to a char array that is equivalent to the full string representation of the byte array stored in x, which is:

00010409101924314051647990A9C4E10021446990B9E4114071A4D9104984C1

Basically, I want to do the programatic equivalent of

char hex[64] = "00010409101924314051647990A9C4E10021446990B9E4114071A4D9104984C1"

How can this be done in C programming language?

Upvotes: 2

Views: 6408

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

You can use sprintf and pass &hex[2*i] for the printing position:

char hex[65];
for (int i = 0 ; i != 32 ; i++) {
    sprintf(&hex[2*i], "%02X", x[i]);
}
hex[64] = '\0';

Since you know that each sprintf will use exactly two positions, you can be sure that 32 sprintf calls will fill all 64 characters in hex[64].

Note: your example tries to store 65 characters in hex[64]. The 65-th one is coming from null terminator of the string literal.

Upvotes: 3

nos
nos

Reputation: 229342

First create a function that converts a nibble (4 bits) to a hex character, e.g.

char to_hex(uint8_t nibble)
{
   static const char hex[] = "0123456789ABCDEF";
   return hex[nibble];
}

Then make a sufficiently large array to hold the result (you need one extra character for the nul terminator, call the to_hex function for each 4 bits.

char result[65];
int i = 0;
uint8_t x[32];

for (i = 0; i < 32; i++) {
    x[i] = i*i;
    result[i*2] = to_hex(x[i] >> 4);  //upper 4 bits
    result[i*2+1] = to_hex(x[i] & 0xf); //lower 4 bits
}
result[64] = 0; //make sure the string is nul terminated
printf("Result is : %s\n", result);

Upvotes: 1

Related Questions