为什么我会得到奇怪的结果,将其移位为负值? [英] Why am I getting strange results bit-shifting by a negative value?

查看:98
本文介绍了为什么我会得到奇怪的结果,将其移位为负值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题不是此问题的重复项.

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

I came across a situation where I might have had to left-shift a (positive) number by a negative value, i.e., 8 << -1. In that case, I would expect the result to be 4, but I'd never done this before. So I made up a little test program to verify my hypothesis:

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

令我震惊和惊讶的是以下输出:

which to my shock and surprise gave me the following output:

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

任何人都可以解释这种行为吗?

Can anyone explain this behaviour?

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

Here's a little bonus. I changed the left-shift to a right-shift, and got this output:

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

推荐答案

您不能移动负值.您也不能将较大的正数移位.

You can't shift by a negative value. You also can't shift by a large positive number.

根据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.

这篇关于为什么我会得到奇怪的结果,将其移位为负值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆