c# – 当操作数为<32位时,为什么移位操作总是导致带符号int
发布时间:2020-12-15 18:03:39 所属栏目:百科 来源:网络整理
导读:为什么在unsigned int上的移位操作给出无符号结果,但是对较小的无符号操作数的操作会导致一个带符号的int? int signedInt = 1;int shiftedSignedInt = signedInt 2;uint unsignedInt = 1;uint shiftedUnsignedInt = unsignedInt 2; //OK. unsigned resultsh
为什么在unsigned 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 解决方法
shift operators仅为这些情况预定义(向左移动):
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 shifUnignedShort = unsignedShort<<< 2被解释为(1)-st情况(implicit up-casting from ushort to int和(int)2),所以它对非法投射执行了一个警告(没有int结果到隐含的转换). 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |