微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/java/123797.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐