gpt4 book ai didi

java - 按负数移位的位移位运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:57:11 32 4
gpt4 key购买 nike

我遇到了一个有趣的场景,在使用位移运算符时。如果第二个操作数是负数,移位运算是如何进行的? .

即 a << b ,“<<”将 a 中的位模式向左移动 b 位。但是如果 b 是负数,它不应该是运行时的错误吗?

我能够成功运行以下代码,但我不明白它是如何工作的?

 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 的偏移 - 因此您看到了结果。

关于java - 按负数移位的位移位运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15603327/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com