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

Problem with Shift-Operator

Hi,

I have a Problem with the Shift-Operator >> within my C-Code.
I'm using PK166 V4.2
The following code should set the Variable n to 0.

void main()
{
 unsigned char n;
 unsigned char p;  // dummy

 n=255;
 n=n>>22;

 p=0;		// dummy

}

With Simulator and real hardware n=3!

The Compiler generates a shift of 22, which is invalid. The Assembler Opcode only evaluates the lower 4 bits of the shift-operand.

Generated Assembler Code:
R4 contains the variable n:

 MOV R5, #0x16 // incorrect Opcode???
 SHR R4,R5

The lower 4 bits of 0x16=0x06, and that is what really happens. ( 255 >> 6 = 3 )

I get the same result with Compiler V5.04.

Is it invalid to shift a byte-variable more than 8 times?
If so, why does the compiler not generate a warning?

Parents

  • How did you stumble across this behaviour?


    For debug-purpose I have written a Marcro that puts a variable (8bit, 16bit, 32bit) into a CAN-Message

    debug_out(val)
    data[0]=(val>>24)&0xFF;
    data[1]=(val>>16)&0xFF;
    data[2]=(val>>8)&0xFF
    data[3]=val&0xFF;
    CANWRITE();
    
    I was surprised that data[0..3] sometimes did not contain 0 although "val" was an 8bit value. I thought that a right-shift would always insert a 0 at the left side and the result would therefore be 0.

    data[0]=(unsigned long) (val>>24);
    data[1]...
    ...
    
    solves the problem.

Reply

  • How did you stumble across this behaviour?


    For debug-purpose I have written a Marcro that puts a variable (8bit, 16bit, 32bit) into a CAN-Message

    debug_out(val)
    data[0]=(val>>24)&0xFF;
    data[1]=(val>>16)&0xFF;
    data[2]=(val>>8)&0xFF
    data[3]=val&0xFF;
    CANWRITE();
    
    I was surprised that data[0..3] sometimes did not contain 0 although "val" was an 8bit value. I thought that a right-shift would always insert a 0 at the left side and the result would therefore be 0.

    data[0]=(unsigned long) (val>>24);
    data[1]...
    ...
    
    solves the problem.

Children