c# - Combine 2 numbers in a byte -
i have 2 numbers (going 0-9) , want combine them 1 byte. number 1 take bit 0-3 , number 2 has bit 4-7.
example : have number 3 , 4.
3 = 0011 , 4 0100.
result should 0011 0100.
how can make byte these binary values?
this 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 code have argumentoutofboundsexceptions
forget bitarray stuff.
just this:
byte result = (byte)(number1 | (number2 << 4));
and them back:
int number1 = result & 0xf; int number2 = (result >> 4) & 0xf;
this works using <<
, >>
bit-shift operators.
when creating byte, shifting number2
left 4 bits (which fills lowest 4 bits of results 0) , use |
or bits unshifted bits of number1
.
when restoring original numbers, reverse process. shift byte right 4 bits puts original number2
original position , use & 0xf
mask off other bits.
this bits number1
in right position (since never shifted them) need mask off other bits, again & 0xf
.
you should verify numbers in range 0..9 before doing that, or (if don't care if they're out of range) can constrain them 0..15 anding 0xf:
byte result = (byte)((number1 & 0xf) | ((number2 & 0xf) << 4));