不能将’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) channel
是ushort
但12 * (ushort)(channel)
将是int
,改为:
ushort quotient = (ushort) ((12 * channel) / 16);
任何int
和较小类型的乘法都会产生int
。 所以在你的情况下12 * ushort
产生int
。
ushort quotient = (ushort)(12 * channel / 16);
请注意,上面的代码并不完全等同于原始样本 – 如果channel
值超出ushort
范围(0 .. 0xFFFF),则对ushort
的channel
转换可能会显着改变结果。 如果它很重要,你仍然需要内部演员。 下面的示例将为channel=0x10000
(这是所讨论的原始样本)产生0
,这与上面更常规的代码(给出49152
结果)不同:
上述就是C#学习教程:不能将’int’类型转换为’ushort’:已经明确表达分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
ushort quotient = (ushort)((12 * (ushort)channel) / 16);
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1034409.html