Javascript右移负数

时间:2016-05-04 08:13:15

标签: javascript

以下是摘录:

var i = 101;
console.log('101: ' +  i.toString(2));
console.log('101 >> 1: ' + (i >> 1).toString(2));

var l = -101;
console.log('-101: ' + l.toString(2));
console.log('-101 >> 1: ' + (l >> 1).toString(2));'

输出:

"101: 1100101"
"101 >> 1: 110010"
"-101: -1100101"
"-101 >> 1: -110011"

为什么-101 >> 1-110011而不是-110010

更新:本书适用于Web开发人员的专业javaScript 解释了js如何存储负数:

  1. 获取负数
  2. 绝对值的二进制表示
  3. 将0替换为1,将1替换为0
  4. 将1添加到第2步的结果
  5. 所以在我的情况-101 >> 1中,我们首先将-101转换为其二进制表示形式:

    1. Math.abs(-101)的二进制表示形式为:

      <00> 0000 0000 0000 0000 0000 0000 0110 0101

    2. 反转0和1:

      1111 1111 1111 1111 1111 1111 1001 1010

    3. 在结尾添加1:

      1111 1111 1111 1111 1111 1111 1001 1011

    4. 现在,将其向右移动1:

      1111 1111 1111 1111 1111 1111 1100 1101

    5. 上面的二进制文件应该是-101 >> 1的正确结果,但是当记录负数的二进制表示时,Javascript只是在正数的二进制表示前面放置一个负号:

      var x = 15;
      console.log(x.toString(2)); // output: 1111
      
      var y = -15;
      console.log(y.toString(2)); // output: -1111
      

      对于我们的示例,这意味着在记录-101 >> 1的结果时,JS将输出minus sign + the binary representation of the positive number。但正数不是101 >> 1,因为101 >> 1会给您:

      (101 >> 1).toString(2);  // output: 110010
      (-101 >> 1).toString(2); // output: -110011, not -110010!
      

      为了得到正确的结果,我们必须颠倒上述步骤1-3:

      1111 1111 1111 1111 1111 1111 1100 1101   // this is the result we get from step 4
      

      通过减1来反向步骤3,我们得到:

      1111 1111 1111 1111 1111 1111 1100 1100
      

      通过反转0和1反转步骤2:

      0000 0000 0000 0000 0000 0000 0011 0011
      

      通过将此二进制文件转换为整数来反转步骤1:

      parseInt(110011, 2); // output: 51
      

      最后,当JS记录-101 >> 1的结果时,它将是minus sign + the binary representation of 51,即:

      (51).toString(2);        // output:  110011
      (-101 >> 1).toString(2); // output: -110011
      

1 个答案:

答案 0 :(得分:0)

请记住,负数存储为2s补码。为简单起见,假设它是1字节有符号整数,则-101将存储为

1 0000 0000 (256)
- 0110 0101 (101)
= 1001 1011 (155 if it were unsigned, -101 in signed)

当移位负数时,右键用1 s代替0 s(否则你会丢失符号位),结果是:

  1001 1011
       >> 1
= 1100 1101

如果它是无符号整数,则为205。然后2s补充它以解决256 - x = 205 =&gt; x = 51

的Ta-DA? :d

相关问题