0

My server receives 6 bytes of data: 2 bytes of head and 1 variable consist of last 4 bytes in Big Endian order (in example below variable is 100000 decimal)

  00000001 head
  00000001
  10100000 start  4 bytes of variable (100000 decimal)
  10000110
  00000001
  00000000

I want to read this variable using this code below (buf contains data above)

 unsigned char buf[MAX_s]; 
 int32_t var = (buf[2] << 24) | (buf[3] << 16) | (buf[4] << 8) | buf[5];
 printf("  %u \n",var);

but expected result isn't 100000, but some other larger number. What i do wrong?

maciekm
  • 257
  • 1
  • 5
  • 28

1 Answers1

1

The 6 bytes you posted, converted to hexadecimal, are:

01 01 A0 86 01 00

If you construe bytes 2-5 as big endian, the combined number is 0xA0860100 = 2693136640. Is that the number you got?

100000 = 0x000186a0. If you expected the number to be 100000, it looks like your bytestream contains little endian data, not big endian. Reverse the converter to fix this:

int32_t var = (buf[5] << 24) | (buf[4] << 16) | (buf[3] << 8) | buf[2];
Multimedia Mike
  • 12,660
  • 5
  • 46
  • 62