不能将’int’类型转换为’ushort’:已经明确表达

我试图明确地将一个int转换成一个ushort,但是我得到的不能将’int’转换为’ushort’

ushort quotient = ((12 * (ushort)(channel)) / 16); 

我正在使用.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 

我宁愿不改变int频道,也不要改变频道。 我该如何解决错误?

(ushort) channelushort12 * (ushort)(channel)将是int ,改为:

 ushort quotient = (ushort) ((12 * channel) / 16); 

任何int和较小类型的乘法都会产生int 。 所以在你的情况下12 * ushort产生int

 ushort quotient = (ushort)(12 * channel / 16); 

请注意,上面的代码并不完全等同于原始样本 – 如果channel值超出ushort范围(0 .. 0xFFFF),则对ushortchannel转换可能会显着改变结果。 如果它很重要,你仍然需要内部演员。 下面的示例将为channel=0x10000 (这是所讨论的原始样本)产生0 ,这与上面更常规的代码(给出49152结果)不同:

 ushort quotient = (ushort)((12 * (ushort)channel) / 16);