Forget all that bitarray stuff.
Just do this:
byte result = (byte)(number1 | (number2 << 4));
And to get them back:
int number1 = result & 0xF;
int number2 = (result >> 4) & 0xF;
This works by using the <<
and >>
bit-shift operators.
When creating the byte, we are shifting number2
left by 4 bits (which fills the lowest 4 bits of the results with 0) and then we use |
to or those bits with the unshifted bits of number1
.
When restoring the original numbers, we reverse the process. We shift the byte right by 4 bits which puts the original number2
back into its original position and then we use & 0xF
to mask off any other bits.
This bits for number1
will already be in the right position (since we never shifted them) so we just need to mask off the other bits, again with & 0xF
.
You should verify that the numbers are in the range 0..9 before doing that, or (if you don't care if they're out of range) you can constrain them to 0..15 by anding with 0xF:
byte result = (byte)((number1 & 0xF) | ((number2 & 0xF) << 4));