gpt4 book ai didi

c# - 为什么我会得到奇怪的结果位移负值?

转载 作者:可可西里 更新时间:2023-11-01 08:18:37 25 4
gpt4 key购买 nike

这个问题不是 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 = 134217728i = -7, 8 << -7 = 268435456i = -6, 8 << -6 = 536870912i = -5, 8 << -5 = 1073741824i = -4, 8 << -4 = -2147483648i = -3, 8 << -3 = 0i = -2, 8 << -2 = 0i = -1, 8 << -1 = 0i = 0, 8 << 0 = 8i = 1, 8 << 1 = 16i = 2, 8 << 2 = 32i = 3, 8 << 3 = 64i = 4, 8 << 4 = 128

谁能解释这种行为?

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

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

最佳答案

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

来自 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# - 为什么我会得到奇怪的结果位移负值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1881455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com