javaintegerbitwise-operatorsbit-shiftbitwise-or

Invert a value of bit in digit


I want to invert a value of bit in digit.

The method should invert value by number of bit, like this:

public static void main(String[] args) {

    int res = flipBit(7,1);
}

public static int flipBit(int value, int bitIndex) {

    String bin = Integer.toBinaryString(value);
    char newChar = (char) (bin.charAt(bitIndex) ^ bin.charAt(bitIndex));
    
    //pseudo code
    bin[bitIndex] = newChar;    
    
    return Integer.parseInt(bin);
}

Solution

  • Mixing mix bitwise operations and strings will not improve the performance and reduces the redubility of code.

    Assuming that bitIndex is zero-based, it might be done using XOR operator like that (credits to @Iłya Bursov since he has pointed out it earlier in the comments):

    public static int flipBit(int value, int bitIndex) {
        if (bitIndex < 0 || bitIndex > 31) {
            throw new IllegalArgumentException();
        }
        
        return value ^ 1 << bitIndex;
    }
    

    Online Demo

    A quick recap on how XOR works.

    1 ^ 1  =>  0
    0 ^ 1  =>  1
    1 ^ 0  =>  1
    0 ^ 0  =>  0
    

    That means zeros 0 in the bit-mask 1 << bitIndex, created by shifting the value of 1 by the given index, will have no impact on the result while applying XOR.

    Only a single significant bit of the mask would interact with the value: if it would encounter 1, this bit would be turned into 0, or if there would be 0 at the same position it would result into 1.

    Example:

    value = 7, index = 2

    111   -   value
     ^
    100   -   bit-mask `1 << bitIndex`
    
    011   -   result is `3`
    

    value = 0, index = 0

    000   -   value
     ^
    001   -   bit-mask `1 << bitIndex`
    
    001   -   result is `1`