为什么对无符号整数的移位操作给出无符号结果,但对较小的无符号操作数的操作会导致有符号的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
Run Code Online (Sandbox Code Playgroud) 我试图明确地将一个int转换成一个ushort,但是我得到的不能将'int'转换为'ushort'
ushort quotient = ((12 * (ushort)(channel)) / 16);
Run Code Online (Sandbox Code Playgroud)
我正在使用.Net Micro框架,因此BitConverter不可用.为什么我首先使用ushort与我的数据如何通过SPI发送有关.我可以理解这个特定的错误已经在这个网站上提出但我不明白为什么当我明确表示我不在乎是否有任何数据丢失,只需将32位切成16位我会很高兴.
public void SetGreyscale(int channel, int percent)
{
// Calculate value in range of 0 through 4095 representing pwm greyscale data: refer to datasheet, 2^12 - 1
ushort value = (ushort)System.Math.Ceiling((double)percent * 40.95);
// determine the index position within GsData where our data starts
ushort quotient = ((12 * (ushort)(channel)) / 16); // There is 12 peices of 16 bits
Run Code Online (Sandbox Code Playgroud)
我宁愿不改变int频道,也不想改变频道.我该如何解决错误?