How do I concatenate 2 bytes?

前端 未结 6 1800
萌比男神i
萌比男神i 2021-02-08 02:18

I have 2 bytes:

byte b1 = 0x5a;  
byte b2 = 0x25;

How do I get 0x5a25 ?

6条回答
  •  后悔当初
    2021-02-08 02:31

    A more explicit solution (also one that might be easier to understand and extend to byte to int i.e.):

    using System.Runtime.InteropServices;
    [StructLayout(LayoutKind.Explicit)]
    struct Byte2Short {
      [FieldOffset(0)]
      public byte lowerByte;
      [FieldOffset(1)]
      public byte higherByte;
      [FieldOffset(0)]
      public short Short;
    }
    

    Usage:

    var result = (new Byte2Short(){lowerByte = b1, higherByte = b2}).Short;
    

    This lets the compiler do all the bit-fiddling and since Byte2Short is a struct, not a class, the new does not even allocate a new heap object ;)

提交回复
热议问题