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:

11000000
Promoting to an int gives:
11111111111111111111111111000000
Shift right unsigned 4 gives:
0000111111111111111111111111111111111100
Truncate to byte gives:
11111100
The expected result may have been:
00001100

No comments: