问题描述
C ++移位运算符<<
不循环.例如,如果您这样做:
C++ shift operator <<
does not cycle. For example if you do:
// C++
int a = 1;
cout << (a<<38);
您获得0.但是,在Java中,您实际上循环并获得了有效值64.
You get 0. But, in Java you actually cycle and get a valid value of 64.
我需要将一些C ++代码转换为Java,所以我怎么用等价于<<
?
I need to translate some C++ code to Java, so what do I use as the equivalent for <<
?
推荐答案
Java语言规范指出:
如果左侧操作数的提升类型很长,则仅 右侧操作数的最低6位用作移位 距离.好像右手操作数受到了 逐位逻辑AND运算符& (§15.22.1)的掩码值为0x3f (0b111111).因此,实际使用的移动距离始终为 范围为0到63(含).
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.
因此,在您的示例情况下,(int)(((long)a)<<38)
应该可以工作.
So, in your example case, (int)(((long)a)<<38)
should work.
这篇关于等效于C ++移位运算符<<在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!