Java – Insert One Bit into Byte Array

binarybit-manipulationbytejava

I'm trying to insert a single bit into an array of bytes, which would shift all the bits in the byte array to the left.

Say I have a Java byte array as follows:

byte[] byteArray = new byte[2];
byteArray[0] = 0x11
byteArray[1] = 0x00

In binary, this byte array represented as:

0001 0001 0000 0000

Now I want to insert a zero in the third bit position (losing the last bit in the byte array), resulting in:

0000 1000 1000 0000

Is there any easy way to do this in Java? I'm aware of the BigInteger class which can convert the entire byte array to a binary String (then insert that way and convert back), but that seems inefficient.

Thanks in advance.

Best Answer

The tricky bit is to shift the character where you actually want to insert the bit, because you only want to shift part of it. That can be done using a function like this:

public static char shift(char in, char n, char v)
{
    char lowMask = (1 << n) - 1;
    char highMask = 0xFF ^ lowMask;

    return (in & lowMask) | ((in & highMask) << 1) | ((v&1) << n);
}

After you've inserted the bit into the first character you'll have to shift the rest of the array as well. That can be done by simply shifting one bit to the right (<< 1) and setting the least significant bit (LSB) of the next character to the state of the most significant bit (MSB) in the last character.