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));
source share