I ran across unexpected behaviour while programming in C for an 8-bit AVR microcontroller: Consider the following:
unsigned char a = 0xFF, b = 0xFF;
unsigned short c = ((a>>4)<<8)+b;
printf("%x",c);
Where the high order nibble of byte a
contains bits 8..11 and the byte b
contains bits 7..0 of a 12-bit value c. The intent of the code was originally to remove the unwanted lower nibble of byte a
, and then combine a
and b
to yield the value of c
. However later on I realized the code should not work, as a
is an 8-bit value, and shifting it 8 bits to the left should result in clearing the byte to 0, and a final result of 0x00FF. Instead, the code produces a result of 0x0FFF, as originally intended. The code produces the same result both on the microcontroller (avr-gcc) and on the PC (gcc). What is the cause of this behaviour?