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
  • Oh, come on, Erik, you surely know better than to believe everything being said about either operand of a two-operand operator like '<<' would automatically apply to both of them. It can't be all that hard to distinguish between the number being shifted, and the number of positions it's shifted by, now can it?

    Negative shift counts are strictly forbidden. Shifts of negative values are implementation-defined. Which, as I said earlier, makes them risky.

    It would be nice if that was CLEAR.

    Being unmistakably clear is about the only thing a standard is required to be at all, besides not directly contradicting itself. I would say the C99 standard is quite clear indeed. It takes a while to get used to the jargon, but that's unavoidable in a text like this, which is effectively a legal and a technical document at the same time.

Reply
  • Oh, come on, Erik, you surely know better than to believe everything being said about either operand of a two-operand operator like '<<' would automatically apply to both of them. It can't be all that hard to distinguish between the number being shifted, and the number of positions it's shifted by, now can it?

    Negative shift counts are strictly forbidden. Shifts of negative values are implementation-defined. Which, as I said earlier, makes them risky.

    It would be nice if that was CLEAR.

    Being unmistakably clear is about the only thing a standard is required to be at all, besides not directly contradicting itself. I would say the C99 standard is quite clear indeed. It takes a while to get used to the jargon, but that's unavoidable in a text like this, which is effectively a legal and a technical document at the same time.

Children
No data