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?

0

1 Answer 1

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]; 
Sign up to request clarification or add additional context in comments.

1 Comment

yes it is this number!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.