Combine 2 numbers in bytes

I have two numbers (from 0 to 9) and I want to combine them into 1 byte. Number 1 will take bit 0-3, and number 2 will take bit 4-7.

Example: I have numbers 3 and 4.
3 = 0011 and 4 - 0100.
The result should be 0011 0100.

How can I make a byte with these binary values?

This is what I have:

public Byte CombinePinDigit(int DigitA, int DigitB) { BitArray Digit1 = new BitArray(Convert.ToByte(DigitA)); BitArray Digit2 = new BitArray(Convert.ToByte(DigitB)); BitArray Combined = new BitArray(8); Combined[0] = Digit1[0]; Combined[1] = Digit1[1]; Combined[2] = Digit1[2]; Combined[3] = Digit1[3]; Combined[4] = Digit2[0]; Combined[5] = Digit2[1]; Combined[6] = Digit2[2]; Combined[7] = Digit2[3]; } 

With this code, I have arguments ArgumentOutOfBoundsExceptions

+4
source share
2 answers

Forget all these things from bitarray.

Just do the following:

 byte result = (byte)(number1 | (number2 << 4)); 

And return them:

 int number1 = result & 0xF; int number2 = (result >> 4) & 0xF; 

This works using the bit-shift operators << and >> .

When creating a byte, we move number2 left by 4 bits (which fills the least 4 bits of the results with 0), and then we use | to or these bits with unbiased bits number1 .

When restoring the original numbers, we cancel the process. We shift the byte by 4 bits, which returns the original number2 to its original position, and then we use & 0xF to mask any other bits.

These bits for number1 will already be in the correct position (since we never shifted them), so we just need to hide the other bits, again with & 0xF .

You must make sure that the numbers are in the range 0..9 before doing this, or (if you do not care if they are outside the allowable range), you can limit them to 0..15 by using with 0xF

 byte result = (byte)((number1 & 0xF) | ((number2 & 0xF) << 4)); 
+5
source

this should basically work:

 byte Pack(int a, int b) { return (byte)(a << 4 | b & 0xF); } void Unpack(byte val, out int a, out int b) { a = val >> 4; b = val & 0xF; } 
+3
source

All Articles