Java中的C shift运算符的等价物?

前端之家收集整理的这篇文章主要介绍了Java中的C shift运算符的等价物?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
C移位运算符<不循环例如,如果你这样做:
// C++
int a = 1;
cout << (a<<38);

你得到0.但是,在Java中,你实际上会循环并获得64的有效值.

我需要将一些C代码翻译成Java,所以我用什么作为<<?

解决方法

Java language spec说:

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.

所以,在你的例子中,(int)(((long)a)<< 38)应该工作.

原文链接:https://www.f2er.com/java/123797.html

猜你在找的Java相关文章