我遇到一个有趣的情况,当使用按位移位运算符.如果第二个操作数为负,则按位移动操作如何工作? .
即< 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的转变结果,因此你看到的结果.