1

I want to combine four single bytes of data to one datum of four bytes.

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

int main(int argc, char *argv[]) {

    unsigned long int sdata = 0x12*(16^6) + 0x34*(16^4) + 0x56*(16^2) + 0x78;
    printf("%x %d", sdata, sizeof(sdata));
    return 0;
}

The screen prints:

c20 4

I want to get:

sdata = 0x12345678

The type unsigned long int is a 4 byte data type, so why can't it save the data? Why is the output wrong?

underscore_d
  • 6,309
  • 3
  • 38
  • 64

2 Answers2

2

You must use binary operations. More precisely left shifts (<<) and binary or (|).

unsigned int sdata = 0x12<<24 | 0x34<<16 | 0x56<<8  | 0x78;
printf("%x %zu\n", sdata, sizeof(sdata));

This yields

12345678 4

chmike
  • 20,922
  • 21
  • 83
  • 106
1

unsigned long int is not always 4 bytes, in many implementations it's 8 bytes.

As was said in the comments ^ does not represent power in C, it's a bitwise operator.

Your printf specifiers are not correct, you should use %lx in the first (or %#lx if you'd like to print the 0x prefix) and %zu in the second.

Demo

Casting to unsigned long will avoid integer overflow, more so because there are some implementations in which int type is 2 bytes in size.

unsigned long int sdata = (unsigned long int)0x12*16*16*16*16*16*16 + (unsigned long int)0x34*16*16*16*16 + 0x56*(16*16) + 0x78;
printf("%#lx %zu", sdata, sizeof(sdata));

Output:

0x12345678 8 //in this demo, as you can see, unsinged long int is 8 bytes

Or just use binary operations if you can, as demonstrated by @chmike

anastaciu
  • 23,467
  • 7
  • 28
  • 53