Home > other >  C - Converting hex into char array
C - Converting hex into char array

Time:10-08

I have an unit32_t in hex format : uint32_t a = 0xdddddddd how can I convert it into an

array[8] = {0,x,d,d,d,d,d,d,d,d}

I tried to use :

for(int i = 0; i < 8; i  ){
array[i] = (a & (0x80 >> i)) > 0;
}

CodePudding user response:

if you are referring to using the array to store every hex digit in a place in the array then you can do:

    for(int i = 0; i < 8; i  ){
        array[i] = a & 0x0F;
        a = a >> 4;
    }

where every time, we get the right most hex digit (which is 4 bits) and assign that to the array and then we shift left a to get the next right most 4 bits as every hex digit is 4 bits indeed.

but if you are referring to converting that hex number into a string then you can use the function called itoa with the base = 16. but notice that itoa() is not a C standard function. It is a non-standard extension provided by a specific implementation.

so you can write:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>


int main(void)
{
    uint32_t a = 0xdddddddd;
    char array[10];
    itoa(a, array, 16);
    printf("array = 0x%s\n", array);
    return 0;
}  

and this is the output:

array = 0xdddddddd

CodePudding user response:

Another conforming implementation can simply use snprintf() as intended to write the representation of the number in a in hex to array. In that case, all that is needed is a sufficiently sized array and:

    snprintf (array, sizeof array, "%x", a);

See: man 3 printf and C18 Standard - 7.21.6.5 The snprintf function

A short example outputting each element of array after filling with a would be:

#include <stdio.h>
#include <stdint.h>

int main (void) {
  
  char array[16] = "";
  uint32_t a = 0xdddddddd;
  
  /* write a to array in hex validatating array was of sufficient size */
  if ((size_t)snprintf (array, sizeof array, "%x", a) >= sizeof array)
    fputs ("warning: representation of 'a' truncated.\n", stderr);
  
  /* output results */
  for (int i = 0; array[i]; i  )
    printf ("array[-] : '%c'\n", i, array[i]);
}

Example Use/Output

$ ./bin/hex2char
array[ 0] : 'd'
array[ 1] : 'd'
array[ 2] : 'd'
array[ 3] : 'd'
array[ 4] : 'd'
array[ 5] : 'd'
array[ 6] : 'd'
array[ 7] : 'd'
  •  Tags:  
  • c
  • Related