How do you convert 3 bytes into a 24 bit number in C#?

后端 未结 5 971
我在风中等你
我在风中等你 2020-12-10 19:15

I have an array of bytes that I read from a header section of a message. These bytes contain the length of the message. There never are more than 3 bytes and they are ordere

相关标签:
5条回答
  • 2020-12-10 19:26

    Use methods like BitConverter.ToInt32, but realize that you'll need 4 bytes for 32 bit quantities.

    var data = new byte[] {39, 213, 2, 0};
    int integer = BitConverter.ToInt32(data, 0);
    

    There are also other methods to convert to and from other types like Single and Double.

    0 讨论(0)
  • 2020-12-10 19:36
    var num = data[0] + (data[1] << 8) + (data[2] << 16);
    
    0 讨论(0)
  • 2020-12-10 19:37

    BitConverter handles the endianness for you which is why it's the way to go.

    While you need 4 bytes, do

    BitConverter.ToInt32(new byte[1] { 0 }.Concat(yourThreeByteArray).ToArray());
    
    0 讨论(0)
  • 2020-12-10 19:40

    Use the Left-shift operator and the or operator:

    int d = (data[2] << 16) | (data[1] << 8) | data[0]
    

    Obviously, you could do all sorts of things here, like using a loop etc :)

    0 讨论(0)
  • 2020-12-10 19:45

    Something like this should work:

    data[0] + 256*data[1] + 256*256*data[2]
    

    Your compiler should optimize that to the 'right' bit twiddling operations.

    0 讨论(0)
提交回复
热议问题