Question

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?

Était-ce utile?

La solution

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

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

Autres conseils

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); 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top