Wednesday, 19 January 2011

Promotion and Reduction of Operands

Reduction of the right operand

If you use a shift number that is greater than the length of the variable type (ie for int this would be a number greater than 32) then the Java compiler will take the modulus of that number. For example: 2 >> 33 would become 2 >> (33 % 32) or 2 >> 1

Promotion of Operands

When shifting number smaller than an int the results can be unexpected. for example consider:
byte b = -64;
byte c = b >>> 4;
The original number will be:

Promoting to an int gives:
Shift right unsigned 4 gives:
Truncate to byte gives:
The expected result may have been:

No comments: