0

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.

3
  • So each byte in the array contains only a nibble, correct? Commented May 5, 2015 at 12:11
  • Yes. That is correct. Commented May 5, 2015 at 12:12
  • Simply listing your requirements and asking for help is not a good way to ask a question on this site. Please see Why is "Can someone Help me" not an "actual" question. Show us how you tried to solve the problem yourself, then show us exactly what the result was, and tell us why you feel it didn't work. Commented May 5, 2015 at 12:17

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.