这个问题并不是一个重复的问题,与这个问题不同。
我遇到了这样一种情况,我需要将一个(正)数左移一个负值,例如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