不能隐式地将类型“int”转换为“ushort”:已经显式转换
本文关键字:ushort 显式转换 转换 int 类型 不能 | 更新日期: 2023-09-27 18:31:26
我正在尝试将一个 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 通道。 如何解决错误?
(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),则 channel
转换为 ushort
可能会显着改变结果。如果它很重要,你仍然需要内部铸件。下面的示例将为channel=0x10000
生成0
(这是有问题的原始示例所做的),这与上面更规则的代码(给出49152
结果)不同:
ushort quotient = (ushort)((12 * (ushort)channel) / 16);