2

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();
    }
2
  • Two bytes does not make an Int32... What rules do you want for the conversion here? Commented Jul 5, 2012 at 22:29
  • bits 0 through 15 would be the Int16 and bits 16 through 31 would be zero. So 0x0800 would be: 0000 0000 0000 0000 0000 1000 0000 0000 Commented Jul 5, 2012 at 22:42

2 Answers 2

4

Why not just use simple bitwise operators? e.g.

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 ..

Sign up to request clarification or add additional context in comments.

Comments

1

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/

2 Comments

I used a decompiler on Jon Skeets .dll and it looks like his EndianBitConverter uses the same bitwise operations pst suggested.
@aelstonjones: Right, but one is more self-explanatory when you see it again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.