由负数转变逐位移位运算 [英] Bit wise shift operator with shift by negative number

查看:180
本文介绍了由负数转变逐位移位运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到一篇有趣的场景,当按位移位运算符的工作。如果第二个操作数是负的,请问按位移位运算的作品? 。

即一个与所述;&下; B,&所述;&下;移动通过在b比特的比特模式到左边。但是,如果b neagtive,应该不是成为一个运行时错误?

我能够到C成功运行低于$ C $,但我不明白它是如何工作的?

 公共静态无效bitwiseleftShift(CHAR testChar)
{
    INT VAL = testChar-A;
    INT结果= 1<< VAL;
    的System.out.println(逐位的1 VAL转变=+ VAL +为+结果);
}

输入

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

结果

 位的1 VAL明智的转变= -32为1
   逐位的1 VAL转变= -49 32768

ASCII为'一'是97有人可以帮助我了解如何工作的?


解决方案

  

但如果b为neagtive,应该不是在运行时错误?


不根据Java语言规范的部分15.19


  

如果左手操作数的提升的类型为int,仅右手操作数的五个最低阶位被用作移位距离。这是因为如果右手操作体进行按位逻辑与运算放大器&; (§15.22.1)与屏蔽值0x1F的(0b11111)。因此实际所用的偏移距离总是在0至31范围,包括


所以-32的转变实际上最终为0的转变,以及-49的转变实际上为15移位结束 - 因此你看到的结果。

I came across an interesting scenario, When working with bitwise shift operator. If the second operand is negative, how does the bitwise shift operation works? .

i.e a << b , "<<" shifts a bit pattern to the left by b bits in a. But if b is neagtive, shouldn't it be an error at runtime ?

I am able to run the below code successfully but I don't understand how it works?

 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);
}

Input

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

Results

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

ASCII for 'a' is 97. Can someone help me understand how this works?

解决方案

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

Not according to the Java Language Specification, 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.

So a shift of -32 actually ends up as a shift of 0, and a shift of -49 actually ends up as a shift of 15 - hence the results you saw.

这篇关于由负数转变逐位移位运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆