Search code examples
javabit-manipulationbit-fields

Efficient way to manipulate bits in byte array representing a bitfield


So, I have a byte array that represents a bitfield. A bit 1 at any index of a byte array implies that I have the corresponding piece and vice versa for a 0. Now, I need to change the bit value of 0 to 1, whenever I have the corresponding piece.

My question is, is it better if I convert the byte array to an int array and then change the corresponding value of the array index or is it simpler to do it in a byte array?

If it's the former, how can I convert the byte array to an integer array? If it's the latter, how do I change the value of the corresponding byte array?


Solution

  • To check if bit n is true

    boolean get(int n, byte[] bitField)
    {
        return (bitField[n >> 3] & 1 << (n & 0x7)) != 0; //or use n / 8 and n % 8
    }
    

    To set bit n

    void set(int n, byte[] bitField, boolean value)
    {
        if(value)
            bitField[n >> 3] |= 1 << (n & 0x7);
        else
            bitField[n >> 3] &= ~(1 << (n & 0x7));
    }
    

    If you use a BitSet, it's a bit simpler

    To instantiate

    BitSet bitField = new BitSet(); //can specify size
    

    To check if bit n is true

    bitField.get(n);
    

    To set bit n

    bitField.set(n, value); //can also use set(int) and clear(int) instead