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

java – 位移位运算符,以负数移位

我遇到一个有趣的情况,当使用按位移位运算符.如果第二个操作数为负,则按位移动操作如何工作? .

即< b,“<”在a中将位模式向左移位b位.但是如果b是neagtive,在运行时不应该是错误? 我能够成功运行下面的代码,但我不明白它是如何工作的?

public static void bitwiseleftShift(char testChar)
{
    int val=testChar-'a';
    int result= 1<<val;
    System.out.println("bit wise shift of 1 with val="+val+" is "+result);
}

输入

bitwiseleftShift('A');// ASCII 65
   bitwiseleftShift('0'); // ASCII 48

结果

bit wise shift of 1 with val=-32 is 1
   bit wise shift of 1 with val=-49 is 32768

“a”的ASCII为97.有人可以帮助我了解这是如何工作的?

解决方法

But if b is neagtive,shouldn’t it be an error at runtime?

不符合Java语言规范section 15.19

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.

所以,-32的转变实际上是0的转变,而-49的转变实际上是以15的转变结果,因此你看到的结果.

原文地址:https://www.jb51.cc/java/125849.html

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

相关推荐