代码之家  ›  专栏  ›  技术社区  ›  Jon Seigel

为什么我会得到一个奇怪的结果,一个负值的移位?

  •  10
  • Jon Seigel  · 技术社区  · 16 年前

    这个问题不是重复的 this question .

    我遇到了一种情况,我可能不得不将一个(正)数字左移一个负值,即8<<-1.在这种情况下,我希望结果是4,但我以前从未这样做过。所以我制定了一个小测试程序来验证我的假设:

    for (int i = -8; i <= 4; i++)
        Console.WriteLine("i = {0}, 8 << {0} = {1}", i, 8 << i);

    i = -8, 8 << -8 = 134217728
    i = -7, 8 << -7 = 268435456
    i = -6, 8 << -6 = 536870912
    i = -5, 8 << -5 = 1073741824
    i = -4, 8 << -4 = -2147483648
    i = -3, 8 << -3 = 0
    i = -2, 8 << -2 = 0
    i = -1, 8 << -1 = 0
    i = 0, 8 << 0 = 8
    i = 1, 8 << 1 = 16
    i = 2, 8 << 2 = 32
    i = 3, 8 << 3 = 64
    i = 4, 8 << 4 = 128

    有人能解释这种行为吗?

    这里有一点奖金。我将左档改为右档,并得到以下输出:

    i = -8, 8 >> -8 = 0
    i = -7, 8 >> -7 = 0
    i = -6, 8 >> -6 = 0
    i = -5, 8 >> -5 = 0
    i = -4, 8 >> -4 = 0
    i = -3, 8 >> -3 = 0
    i = -2, 8 >> -2 = 0
    i = -1, 8 >> -1 = 0
    i = 0, 8 >> 0 = 8
    i = 1, 8 >> 1 = 4
    i = 2, 8 >> 2 = 2
    i = 3, 8 >> 3 = 1
    i = 4, 8 >> 4 = 0
    2 回复  |  直到 9 年前
        1
  •  18
  •   Aaron    16 年前

    从C#spec( http://msdn.microsoft.com/en-us/library/a1sway8w.aspx ):

    If first operand is an int or uint (32-bit quantity), 
    the shift count is given by the low-order five bits of second operand.
    
    ...
    
    
    The high-order bits of first operand are discarded and the low-order 
    empty bits are zero-filled. Shift operations never cause overflows.
    
        2
  •  11
  •   bobince    16 年前

    << -1 不能翻译成 >> 1 -1 << 31 .

    您将从JavaScript中获得相同的结果 javascript:alert(8<<-8) .