Search code examples
cavr

32-Bit variable shifting in 8-bit MCU


I'm using 32-bit variable for storing 4 8-bit values into one 32-bit value.

32_bit_buf[0]= cmd[9]<<16 | cmd[10]<<8| cmd[11] <<0;

cmd is of unsigned char type with data

cmd [9]=AA
cmd[10]=BB
cmd[11]=CC

However when 32-bit variable is printed I'm getting 0xFFFFBBCC.

Architecture- 8-bit AVR Xmega

Language- C

Can anyone figure out where I'm going wrong.


Solution

  • Your architecture uses 16bit int, so shifting by 16 places is undefined. Cast your cmd[9] to a wider type, e.g. (uint32_t)cmd[9] << 16 should work.

    You should also apply this cast to the other components: When you shift cmd[10] by 8 places, you could shift into the sign-bit of the 16bit signed int your operands are automatically promoted to, leading to more strange/undefined behavior.