简体   繁体   中英

Converting from base 16 to base 10 in reverse byte order

I am reading data from a network stream from hardware that starts with a fixed header followed by the length of expected data as a System.UInt16 whose first byte is 0x23 and the second byte is 0x00. The order of the bytes is supposed to be reversed according to the hardware documentation and the value I should expect to convert this ushort into is 35 which is 23 converted from base 16 to base 10.

How could I make this conversion programatically considering the reverse ordered bytes. I am using BinaryReader.ReadUInt16() at the moment.

UPDATE: Please note that I am not looking to convert to string using System.Convert.ToString(value, base) for example.

Does this work for your?

byte a1 = 0x23;
byte a2 = 0x00;

ushort a12 = (ushort)(a1 << 8 | a2); //This what you receive
ushort a21 = (ushort)((a12 & 0xFF00) >> 8 | (a12 & 0xFF) << 8);

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