为什么右位移不产生负数 [英] why right bit shifting not producing negative number

查看:94
本文介绍了为什么右位移不产生负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么右移不产生负数!



 Console.WriteLine( 1 <<  2 );  //  结果是4-true我理解;  
Console.WriteLine( 4 >> 4 ); // 结果为0-为什么???????????? ???

解决方案

简单。只需查看二进制值:

 1 == 00000001 
2 == 00000010
3 == 00000011
4 = = 00000100
5 == 00000101

使用移位运算符时,将二进制值n位向左或向右移动。

所以1 左移2个地方:

 0001变为0100 
18



和4 右移4个地方:

 0100变为0000 
40

因为所有1位都被移出价值和丢弃。

转移就是这样 - 它不会将值包裹回到值的顶部或底部。


这是右移的方式,即(来自 MSDN [ ^ ]):



右移:

int operator>>(int x,int count);

uint operator>>(uint x ,int count);

long运算符>>(long x,int count);

ulong运算符>>(ulong x,int count);

>>运算符将x右移一个按如下所述计算的位数。

当x的类型为int或long时,丢弃x的低位,其余位向右移位,如果x为非负,则高位空位位置设置为零;如果x为负,则设置为1。





所以,十进制 4 ,即(二进制) 100b ,变为 0

 100b>>  1  = 010b 
100b>> 2 = 001b
100b>> 3 = 000b
100b>> 4 = 000b
...


why right bit shifting not producing negative number!

Console.WriteLine(1 << 2 );//result is 4-true i understand;
Console.WriteLine(4 >> 4);//result is 0-why??????????????

解决方案

Simple. Just look at the values in binary:

1 ==   00000001
2 ==   00000010
3 ==   00000011
4 ==   00000100
5 ==   00000101

When you use a shift operator, you move the binary value "n" bits to the left or right.
So "1" left shifted 2 places:

0001  becomes 0100
   1     "       8


And "4" right shifted 4 places:

0100 Becomes 0000
   4    "       0

because all the "1" bits are shifted out of teh value and discarded.
A "shift" is just that - it does not "wrap" bits back to teh top or bottom of the value.


That's the way right shift works, namely (from MSDN[^]):

Shift right:
int operator >>(int x, int count);
uint operator >>(uint x, int count);
long operator >>(long x, int count);
ulong operator >>(ulong x, int count);
The >> operator shifts x right by a number of bits computed as described below.
When x is of type int or long, the low-order bits of x are discarded, the remaining bits are shifted right, and the high-order empty bit positions are set to zero if x is non-negative and set to one if x is negative.



So, decimal 4, that is (binary) 100b, becomes 0:

100b >> 1 = 010b
100b >> 2 = 001b
100b >> 3 = 000b
100b >> 4 = 000b
...


这篇关于为什么右位移不产生负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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