简体   繁体   English

C#-尝试将两个字节转换为ushort导致错误“无法将类型'int'隐式转换为'ushort'”错误

[英]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. 该代码的目的是将两个字节合并为ushort。 All variables are ushort type, but M_hi and M_lo are loaded with a byte. 所有变量均为ushort类型,但是M_hi和M_lo加载了一个字节。 I originally had them as just bytes, but this error happened so I tried ushort instead The first part masks off the higher byte. 我本来只是字节而已,但是发生此错误,所以我改用ushort代替。第一部分掩盖了较高的字节。 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. 然后将其与0x100相乘,从而有效地将其移至更高字节的位置。 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). 这些值是从字节数组读取的,该字节数组将数据存储在little-endian中,因此我需要执行以下操作以将它们组合起来以使用ushort值(不,我无法将整个数组转换为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. 我也尝试过检查ToInt16方法,但是Unity似乎没有。

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. 根据https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/ushort#conversions,在添加两个类型为ushort的变量时,结果为int。 This means that the actual type of ((cv.M_hi & 0x00FF) * 0x100) + cv.M_lo; 这意味着((cv.M_hi & 0x00FF) * 0x100) + cv.M_lo;的实际类型((cv.M_hi & 0x00FF) * 0x100) + cv.M_lo; is int . int

This can be easily fixed with an explicit cast: 这可以通过显式强制转换轻松解决:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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