为什么移位操作总是导致一个符号整数运算时为< 32位 [英] Why do shift operations always result in a signed int when operand is <32 bits

查看:204
本文介绍了为什么移位操作总是导致一个符号整数运算时为< 32位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么移位运算无符号整数给出一个无符号的结果,但在较小的无符号运算操作导致符号int?

  INT signedInt = 1; 
INT shiftedSignedInt = signedInt<< 2;

UINT无符号整型= 1;
UINT shiftedUnsignedInt =无符号整型<< 2; //好。无符号结果

短signedShort = 1;
INT shiftedsignedShort = signedShort<< 2;

USHORT unsignedShort的= 1;
UINT shiftedUnsignedShort = unsignedShort的<< 2; // CS0266:不能投INT为uint

为sbyte signedByte = 1;
INT shiftedSignedByte = signedByte<< 2;

UnsignedByte的字节= 1;
UINT shiftedUnsignedByte =&UnsignedByte的LT;< 2; // CS0266:不能投INT为uint


解决方案

转移只针对这些情况下预定义运算符(左移):

  INT运营商的LT;≤(INT X,诠释计数); (1)
UINT运营商的LT;≤(UINT X,诠释计数); (2)
长期运营商的LT;≤(长×,诠释计数); (3)
ULONG运营商的LT;≤(ULONG X,诠释计数); (4)



表达式 UINT shiftedUnsignedShort = unsignedShort的<< 2 被解释为:(1)-st情况下(隐含从USHORT了铸造为int (INT)2 ),所以非法铸件进行警告(有从int结果没有隐式转换为USHORT)。结果
同样的情况,我们可以看到 UINT shiftedUnsignedByte =&UnsignedByte的LT;< 2 。这也解释为(1)-st情况下(隐含了铸造从byte到int和(INT)2 ,但得到的值没有隐式转换为uint)。



您可以使用以下方法解决这些问题:

  UINT shiftedUnsignedShort =(UINT)unsignedShort的<< 2 //强制使用(2)-Nd移位运算符的情况下
UINT shiftedUnsignedByte =(UINT) - UnsignedByte的LT;< 2; //强制使用(2)-nd移位运算符的情况下


Why do shift operations on unsigned ints give an unsigned result, but operations on smaller unsigned operands result in a signed 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

解决方案

The shift operators are predefined only for these cases (shift left):

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)

The expression uint shiftedUnsignedShort = unsignedShort << 2 is interpreted as (1)-st case (implicit up-casting from ushort to int and (int)2), so it performed a warning on illegal casting (there is no implicit cast from int result to ushort).
The same situation we can see for uint shiftedUnsignedByte = unsignedByte << 2. It also interpreted as (1)-st case (implicit up-casting from byte to int and (int)2 ,but no implicit cast of resulting value to uint).

You can resolve these issues using the following approach:

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

这篇关于为什么移位操作总是导致一个符号整数运算时为&lt; 32位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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