Cannot implicity convert type 'int' to 'ushort' : already explicity cast

て烟熏妆下的殇ゞ 提交于 2019-12-21 17:23:32

问题


I am trying to explicity cast an int into a ushort but am getting the Cannot implicity convert type 'int' to 'ushort'

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

I am using .Net Micro framework so BitConverter is unavailable. Why I am using ushort in the first place has to do with how my data is being sent over SPI. I can understand this particular error has been brought up before on this site but I cannot see why when I am explicity declaring that I dont care if any data goes missing, just chop the 32 bit into a 16 bit and I will be happy.

            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

I would prefer not to change int channel, to ushort channel. How can I solve the error?


回答1:


(ushort) channel is ushort but 12 * (ushort)(channel) would be int, do this instead:

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



回答2:


Multiplication of any int and smaller types produces int. So in your case 12 * ushort produces int.

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

Note that above code is not exactly equivalent to original sample - the cast of channel to ushort may significantly change result if value of channel is outside of ushort range (0.. 0xFFFF). In case if it is important you still need inner cast. Sample below will produce 0 for channel=0x10000 (which is what original sample in question does) unlike more regular looking code above (which gives 49152 result):

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


来源:https://stackoverflow.com/questions/18798666/cannot-implicity-convert-type-int-to-ushort-already-explicity-cast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!