6

我正在尝试将 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 频道。我该如何解决这个错误?

4

2 回答 2

11

(ushort) channelis ushortbut 12 * (ushort)(channel)would be int,改为这样做:

ushort quotient = (ushort) ((12 * channel) / 16);
于 2013-09-14T05:36:43.773 回答
4

int任何和更小类型的乘法产生int. 所以在你的情况下12 * ushort产生int.

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

请注意,上面的代码并不完全等同于原始示例 -如果值超出范围 (0.. 0xFFFF) , channelto 的转换可能会显着改变结果。如果它很重要,你仍然需要内部演员。与上面更常规的代码(给出结果)不同,下面的示例将产生(这是有问题的原始示例所做的):ushortchannelushort0channel=0x1000049152

ushort quotient = (ushort)((12 * (ushort)channel) / 16); 
于 2013-09-14T05:38:36.093 回答