This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

C51 Compiler: Inconsistent Behaviour of Bit Shift Operator (<<)

Compiler Version: Keil C51 5.0

I experienced some unexpected behaviour with the Keil C51 compiler. I have recreated the issue in the below code snippets.

Case 1: Result of bit shift operator is type casted from uchar (8b) to ulong (32b) correctly

unsigned long tempadcVal;
unsigned char data_save_high = 0xA4;
unsigned char data_save_low = 0x3F;
//The expected 32b value without any information loss
//Is loaded into tempadcVal
tempadcVal = (data_save_high<<2) + (data_save_low>>6);

Case 2: Result of bit shift operator is not type casted from uint (16b) to ulong (32)

unsigned long modulated;
unsigned int value = 0xA43F;
modulated = value<<8;
//Here we have modulated = 0x00003F00 (Wrong!)
//Top 8 bits are wiped out

Is this behaviour by design or perhaps a mistake in the compiler?

Parents
  • The compiler does its maths as int (16 bit) so shuffling the 0xA43F by 8 left will produce 0x3F00. That 16 bit result is then promoted to a 32 bit value.

    If you want to keep the detail, you need to ensure the maths is done as 32 bit, such as:

    modulated = ((unsigned long) value) << 8;

Reply
  • The compiler does its maths as int (16 bit) so shuffling the 0xA43F by 8 left will produce 0x3F00. That 16 bit result is then promoted to a 32 bit value.

    If you want to keep the detail, you need to ensure the maths is done as 32 bit, such as:

    modulated = ((unsigned long) value) << 8;

Children