如果我们向左和向左移动最多变为1然后如何计算?

时间:2016-12-10 12:02:11

标签: java bit-manipulation bit-shift

我遇到了一个奇怪的问题。这是代码:

public class ShiftLeft {

 public static void main(String[] args) {

      int c = 22;
      int d = c << 3;
      System.out.println("c << 3 = "+d);
 }

}

答案是:176但是让我们手工计算。

+22 = 0001 0110
      1011 0000 <<3

由于最左边的位是1所以它必须是负数。

Sign + magnitude = 1011 0000
       magnitude =  011 0000
                    100 1111 ---1s compliment


101 0000 ---2s compliment
adding left bit    1101 0000 =-80

只有当我们不计算最左边的位作为符号时才会回答176。这是为什么?

3 个答案:

答案 0 :(得分:4)

因为int的位数超过8位。

答案 1 :(得分:2)

32位整数 0000 0000 0000 0000 0000 0000 1011 0000不是否定的。

答案 2 :(得分:2)

您正在考虑int0000 0000 0000 0000 0000 0000 0001 0110)与byte0001 0110)的关系。但int基元类型有32位(双字),而不仅仅是8位。

0000 0000 0000 0000 0000 0000 0001 0110 (2)
<<
3
=
0000 0000 0000 0000 0000 0000 1011 0000 (2)
=
176 (10)