简体   繁体   中英

c# Combine byte array and convert to a 16-bit Integer

Lets say I have a byte array defined like this:

byte[] byteArray = { 0x08, 0x00 };

I need to combine the elements in the array to create:

0x0800

Then convert that to an int:

2048

Something like this:

    private static int GetMessageType(byte[] byteArray)
    {
        if(byteArray.Length != 2)
            throw new ArgumentOutOfRangeException("byteArray");

        throw new NotImplementedException();
    }

Why not just use simple bitwise operators? eg

byte hiByte = byteArray[0];  // or as appropriate
byte lowByte = byteArray[1];
short val = (short)((hiByte << 8) | lowByte);

In this case the bitwise result is treated as a [signed] short (following the title?) and could result in a negative value, but that can be altered as needed by just removing the cast ..

You should use BitConverter.ToInt16 , except it appears that you want a BigEndian conversion. So use Jon Skeet's EndianBitConverter : http://www.yoda.arachsys.com/csharp/miscutil/

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