当操作数<32位时,为什么shift操作总是导致signed int
为什么对无符号整数的移位操作给出无符号结果,但对较小的无符号操作数的操作会导致有符号的int?
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 case( 从ushort隐式向上转换为int和(int)2
),因此它对非法转换执行警告(没有来自int的隐式转换结果为ushort)。
对于uint shiftedUnsignedByte = unsignedByte << 2
我们可以看到相同的情况uint shiftedUnsignedByte = unsignedByte << 2
。 它也被解释为(1)-st case(从byte到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文章中提到,预定义的移位运算符仅存在于int,uint,long,ulong类型中。 对于所有其他类型,它们都是超载的。 对于所有移位操作,第二个操作数应始终为int
类型。 因此,在执行换档操作之前,任何短型始终都会转换为int。
根据维基百科 <<
和>>
代表两个不同的运营商。 逻辑移位vor ulong和uint以及int和long的算术移位。
现在我的猜测(!)是,“未定义”的ushort或ubyte被转换为int而不是uint。
对不起,但这就是我所能提供的。