How do I concatenate 2 bytes?

前端 未结 6 1814
萌比男神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:36

    It can be done using bitwise operators '<<' and '|'

    public int Combine(byte b1, byte b2)
    {
        int combined = b1 << 8 | b2;
        return combined;
    }
    

    Usage example:

    [Test]
    public void Test()
    {
        byte b1 = 0x5a;
        byte b2 = 0x25;
        var combine = Combine(b1, b2);
        Assert.That(combine, Is.EqualTo(0x5a25));
    }
    

提交回复
热议问题