Convert each byte of an unsigned long to an element of an unsigned char array

-1

If I have this unsigned long x (4 bytes), how I could convert each byte of the x in its hexadecimal equivalent and store all of them in the array: unsigned char[4]?

UPDATE

Based on then sugestions I got, I have tried this two solutions:

solution 1:

  unsigned char hex_str[9];
  snprintf(hex_str, sizeof(hex_str), "%lX", target_hexstr);
  printf("hex_str: %s\n", hex_str);
  printf("size: %lu\n", sizeof(hex_str));
  for(int x=0; x<sizeof(hex_str); x++)
    printf("%x\n", hex_str[x]);

in this case, hex_str displays 1400 and 9 "units": 31, 34, 30, 30, 0, 0, 0, 0, 24.

solution 2:

  hexstr[0] = (x & 0xFF000000) >> 24;
  printf("%x\n", x[0]);
  hexstr[1] = (hexstr & 0x00FF0000) >> 16;
  printf("%x\n", x[1]);
  hexstr[2] = (hexstr & 0x0000FF00) >> 8;
  printf("%x\n", x[2]);
  hexstr[3] = (hexstr & 0x000000FF);
  printf("%x\n", x[3]);
  printf("hex_str: %s\n", hex_str);

in this case, hex_str display nothing and 4 "units": 0, 0, 14, 0.

Why this 2 solutions have differents results?

c
char
type-conversion
long-integer
unsigned
asked on Stack Overflow Aug 27, 2017 by Kleber Mota • edited Aug 27, 2017 by Kleber Mota

1 Answer

2

Because i like bitwise operations iam gonna show you what i would do. But @BLUEPIXY's solution is way more elegant.

We will need

  • & bitwise and
  • >> bitwise shift right

Here is the simple solution, where we are expecting UL as 4B.

unsigned long x = 42;
unsigned char uc[4];

uc[0] = (x & 0x000000FF);
uc[1] = (x & 0x0000FF00) >> 8;
uc[2] = (x & 0x00FF0000) >> 16;
uc[3] = (x & 0xFF000000) >> 24;

printf("uc[0] = %x \n", uc[0]);
printf("uc[1] = %x \n", uc[1]);
printf("uc[2] = %x \n", uc[2]);
printf("uc[3] = %x \n", uc[3]);
answered on Stack Overflow Aug 27, 2017 by Filip Kočica • edited Aug 27, 2017 by Filip Kočica

User contributions licensed under CC BY-SA 3.0