简体   繁体   中英

C# - Trying to convert two bytes to ushort resulting to “Cannot implictly convert type 'int' to 'ushort'” error

The purpose of the code is to combine two bytes to ushort. All variables are ushort type, but M_hi and M_lo are loaded with a byte. I originally had them as just bytes, but this error happened so I tried ushort instead The first part masks off the higher byte. I originally tried to use this to prevent this error because I thought the compiler thinks it might overflow. Although it didn't fix it but I decided to leave it in for now. Then it is multiplied with 0x100 which effectively moves it to the position of the higher byte. Finally adding the second value as the low byte.

cv.M = ((cv.M_hi & 0x00FF) * 0x100) + cv.M_lo;

The values are read from a byte array which stores data in little-endian so I need to do something like this to combine them to use ushort values (And no, I can't convert the entire array to big-endian).

Either way, I know that the algorithm I'm using should work, but there is something that prevents this from working as is. Are there any other ways of doing this? I have also tried checking the ToInt16 method but Unity doesn't seem to have that.

According to https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ushort#conversions when adding two variables of type ushort the result is an int. This means that the actual type of ((cv.M_hi & 0x00FF) * 0x100) + cv.M_lo; is int .

This can be easily fixed with an explicit cast:

cv.M = (ushort)( ((cv.M_hi & 0x00FF) * 0x100) + cv.M_lo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM