【问题标题】:Why am I getting strange results bit-shifting by a negative value?为什么我得到一个负值位移的奇怪结果?
【发布时间】:2009-12-10 23:00:23
【问题描述】:

此问题与this question 不重复。

我遇到了一种情况,我可能不得不将(正)数左移一个负值,即 8

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

令我震惊和惊讶的是,它给了我以下输出:

i = -8, 8 

谁能解释这种行为?

这里有一点好处。我将左移更改为右移,并得到以下输出:

i = -8, 8 >> -8 = 0
我 = -7, 8 >> -7 = 0
我 = -6, 8 >> -6 = 0
我 = -5, 8 >> -5 = 0
我 = -4, 8 >> -4 = 0
我 = -3, 8 >> -3 = 0
我 = -2, 8 >> -2 = 0
我 = -1, 8 >> -1 = 0
我 = 0, 8 >> 0 = 8
我 = 1, 8 >> 1 = 4
我 = 2, 8 >> 2 = 2
我 = 3, 8 >> 3 = 1
i = 4, 8 >> 4 = 0

【问题讨论】:

    标签: c# bit-shift


    【解决方案1】:

    您不能移动负值。你也不能移动一个很大的正数。

    来自 C# 规范 (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】:

      在类 C 语言中,&lt;&lt; -1 不会转换为 &gt;&gt; 1。取而代之的是移位的最低有效 5 位,其余的被忽略,因此在这种情况下,二进制补码 -1 转换为 &lt;&lt; 31

      你会从例如得到相同的结果。 JavaScript javascript:alert(8&lt;&lt;-8).

      【讨论】:

        猜你喜欢
        • 2013-05-12
        • 1970-01-01
        • 1970-01-01
        • 2020-09-21
        • 2014-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多