简体   繁体   中英

Converting Byte Array into short - strange results

I am converting an 2 bytes long byte array into an short (Int16) and showing it via a messagebox.

MessageBox.Show(BitConverter.ToString(arr) + "\n" + BitConverter.ToInt16(arr, 0));

But the results are a bit strange. Here a few examples:

Array    Short   Correct Result
-------------------------------
00-60    24576            24576
AB-2A    10923            10923
55-55    21845            21845
00-80   -32768            32768
AB-AA   -21845            43691
55-D5   -10923            54613  

You're using ToInt16 , which returns numbers from -32768 to 32767, so numbers out of range will be truncated or adjusted to fit the range. For numbers from 0 through 65535, which seems to be what you want, use ToUInt16 instead:

MessageBox.Show(BitConverter.ToString(arr) + "\n" + BitConverter.ToUInt16(arr, 0));

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