为什么对无符号整数的移位操作给出无符号结果,但对较小的无符号操作数的操作会导致有符号的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
。它也被解释为(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
在 转移运营商 MSDN文章中提到,预定义的移位运算符仅存在于int,uint,long,ulong类型中。对于所有其他类型,它们都是超载的。对于所有移位操作,第二个操作数应始终为类型 int
。因此,在执行换档操作之前,任何短型始终都会转换为int。
根据 维基百科 <<
和 >>
代表两个不同的运营商
逻辑移位vor ulong和uint以及int和long的算术移位。
现在我的猜测(!)是,“undefined”ushort或ubyte被转换为int
而不是一个uint。
对不起,但这就是我所能提供的。