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的转变结果,因此你看到的结果.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...