Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate 2 bytes?

Tags:

c#

byte

I have 2 bytes:

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

How do I get 0x5a25 ?

like image 262
jawal Avatar asked Dec 20 '09 10:12

jawal


People also ask

How do you concatenate bytes?

The concat() method of Bytes Class in the Guava library is used to concatenate the values of many arrays into a single array. These byte arrays to be concatenated are specified as parameters to this method. returns the array {1, 2, 3, 4, 5, 6, 7}.

How do I combine two bytes in Python?

To join a list of Bytes, call the Byte. join(list) method. If you try to join a list of Bytes on a string delimiter, Python will throw a TypeError , so make sure to call it on a Byte object b' '. join(...)

Can you add bytes together in Java?

The addition of two-byte values in java is the same as normal integer addition. The byte data type is 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).

How can I add two byte arrays?

To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.


2 Answers

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));
}
like image 187
Elisha Avatar answered Sep 18 '22 02:09

Elisha


Using bit operators: (b1 << 8) | b2 or just as effective (b1 << 8) + b2

like image 26
Nick Fortescue Avatar answered Sep 19 '22 02:09

Nick Fortescue