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

Michael picture Michael · Sep 14, 2013 · Viewed 18.2k times · Source

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?

Answer

King King picture King King · Sep 14, 2013

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

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