0

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.

Vinod kumar
  • 67
  • 1
  • 11

2 Answers2

5

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.

0

That is because you are trying to shift value in 8 bit container (unsigned char) and get a 32 bit. The 8-bit value will be expanded to int (16 bit), but this is still not enough. You can solve the issue in many ways, one of them for e.g. could be by using the destination variable as accumulator.

32_bit_buf[0] = cmd[9];
32_bit_buf[0] <<= 8;
32_bit_buf[0] |= cmd[10];
32_bit_buf[0] <<= 8;
32_bit_buf[0] |= cmd[11];
ivand58
  • 773
  • 6
  • 19
  • Sorry but there's no "8bit container". The operands are promoted to signed `int`. The suggested solution works but the explanation is wrong. –  Nov 07 '17 at 07:31