sunisiha
sunisiha

Reputation: 57

How to split byte array and assign to a byte variable?

In my C# Application, I have a byte array as follows.

byte[] byteArray = {0x2, 0x2, 0x6, 0x6};

I need to split the first two elements i.e 0x2 and 0x2 and assign it to a byte variable. Similarly last two elements should be assigned to another byte variable.

i.e

byte FirstByte = 0x22;
byte SecondByte = 0x66;

I can split the array into sub arrays but I am not able find a way to convert byteArray into a single byte.

Upvotes: 0

Views: 222

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109822

You can just bitwise OR them together, shifting one of the nibbles using <<:

byte firstByte  = (byte)(byteArray[0] | byteArray[1] << 4);
byte secondByte = (byte)(byteArray[2] | byteArray[3] << 4);

You didn't specify the order in which to combine the nibbles, so you might want this:

byte firstByte  = (byte)(byteArray[1] | byteArray[0] << 4);
byte secondByte = (byte)(byteArray[3] | byteArray[2] << 4);

Upvotes: 4

Related Questions