这个问题不是这个问题的重复.
我遇到了一种情况,我可能不得不将(正)数字左移一个负值,即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
Aaron.. 16
你不能换一个负值.你也不能换一个大的正数.
来自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.
bobince.. 9
在类C语言<< -1
中没有翻译成>> 1
.取而代之的是最不重要的5位移位,其余的被忽略,因此在这种情况下,二进制补码-1
转换为<< 31
.
你会从例如得到相同的结果.JavaScript javascript:alert(8<<-8)
.
你不能换一个负值.你也不能换一个大的正数.
来自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.
在类C语言<< -1
中没有翻译成>> 1
.取而代之的是最不重要的5位移位,其余的被忽略,因此在这种情况下,二进制补码-1
转换为<< 31
.
你会从例如得到相同的结果.JavaScript javascript:alert(8<<-8)
.