Insert one bit into a byte array

I am trying to insert one bit into a byte array that will shift all 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 form, this array of bytes is represented as:

 0001 0001 0000 0000 

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

 0000 1000 1000 0000 

Is there an easy way to do this in Java? I know the BigInteger class, which can convert the entire byte array to a binary string (then paste this path and convert back), but it seems inefficient.

Thanks in advance.

+4
source share
4 answers

A complex bit is the offset of a character in which you really want to insert a bit, because you only want to move part of it. This can be done using the following function:

 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 have inserted a bit into the first character, you will also have to shift the rest of the array. This 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.

+7
source

You will want to use bitmask and bitrate. This bit of Java documentation may be useful to you:

http://72.5.124.55/docs/books/tutorial/java/nutsandbolts/op3.html

To be precise, you probably want to convert your byte array to an integer, create a variable for your least significant bits and copy them, set the mask (using the AND mask) these bits from your original variable, the bit shift of the original variable, then the bitmask back (with using the mask OR) the lower digits that you saved.

+2
source

Check out the BitSet class. It can do what you need is pretty trivial.

+1
source

This function works on one byte here, you can convert to unicode CHAR if you need to do something more:

 static byte InsertBit(byte original, byte location) { byte highBits=original & ~(1<<location-1) ; byte lowBits = (1 << location - 1) & (original >> 1); return (1<< location) | highBits |lowBits; } 
0
source

All Articles