问题
C++ shift operator <<
does not cycle. For example if you do:
// C++
int a = 1;
cout << (a<<38);
You get 0. But, in Java you actually cycle and get a valid value of 64.
I need to translate some C++ code to Java, so what do I use as the equivalent for <<
?
回答1:
The Java language spec states:
If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.
If the promoted type of the left-hand operand is long, then only the six lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x3f (0b111111). The shift distance actually used is therefore always in the range 0 to 63, inclusive.
So, in your example case, (int)(((long)a)<<38)
should work.
回答2:
If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.
Please refer to Java Language Specification: http://docs.oracle.com/javase/specs/jls/se7/jls7-diffs.pdf
来源:https://stackoverflow.com/questions/14344546/equivalent-of-c-shift-operator-in-java