Consider the following code:
#include <hal_types.h>
int main() {
uint16 crc16; // hal_types.h: typedef unsigned short uint16;
crc16 = 0x43; // debugger: crc16 == 0x0043, as expected
crc16 = crc16 << 8; // crc16 == 0x0000 ????
return 0;
}
This code is running on a TI CC1111 SoC (with an 8051 core), and compiled/debugged using IAR EW8051 8.10.3, configured to use the C99 dialect, with no optimization. The values in the comments were observed with the IAR debugger (same results using either simulator or actual device).
I would expect that after crc16 = crc16 << 8;
, crc16
would have the value 0x4300
, not 0x0000
.
According to the C99 standard (well, the May 2005-05-06 draft), section 6.5.7.3-4.
The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
My take on this is that the result type should be an unsigned 16-bit integer, with the value ((0x0043)*(2^8)) % 0x10000 == 0x4300
.
Am I missing something? Thanks.