为什么对无符号整数进行移位运算会得到无符号结果,而对较小的无符号操作数进行运算会得到有符号整数?
int signedInt = 1;
int shiftedSignedInt = signedInt << 2;
uint unsignedInt = 1;
uint shiftedUnsignedInt = unsignedInt << 2; //OK. unsigned result
short signedShort = 1;
int shiftedsignedShort = signedShort << 2;
ushort unsignedShort = 1;
uint shiftedUnsignedShort = unsignedShort << 2; //CS0266: Can't cast int to uint
sbyte signedByte = 1;
int shiftedSignedByte = signedByte << 2;
byte unsignedByte = 1;
uint shiftedUnsignedByte = unsignedByte << 2; //CS0266: Can't cast int to uint
移位运算符仅在以下情况下预定义(向左移位):
int operator <<(int x, int count); (1)
uint operator <<(uint x, int count); (2)
long operator <<(long x, int count); (3)
ulong operator <<(ulong x, int count); (4)
表达式uint shiftedUnsignedShort = unsignedShort << 2
被解释为(1)-st大小写(从ushort到int和(int)2
的隐式上转换),因此它对非法转换执行了警告(从int result到ushort没有隐式转换)
我们可以在uint shiftedUnsignedByte = unsignedByte << 2
中看到同样的情况。它也被解释为(1)-st情况(从字节到int和(int)2
的隐式上转换,但没有将结果值隐式转换为uint)。
您可以使用以下方法解决这些问题:
uint shiftedUnsignedShort = (uint)unsignedShort << 2 //force use the (2)-nd shift operator case
uint shiftedUnsignedByte = (uint)unsignedByte << 2; //force use the (2)-nd shift operator case
在Shift运算符MSDN文章中提到,预定义的Shift运算符只存在于int、uint、long和ulong类型中。对于所有其他类型,它们都是重载的。对于所有移位操作,第二个操作数应始终为int
类型。因此,在执行移位操作之前,任何短类型总是被强制转换为int。
根据维基百科,<<
和>>
代表两种不同的运算符。逻辑移位为ulong和uint,算术移位为int和long。
现在我的猜测(!)是,"未定义"的ushort或ubyte被转换为int而不是uint。
对不起,我只能提供这些。