Equivalent of C++ shift operator << in Java?

江枫思渺然 提交于 2019-12-08 15:53:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!