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);
}
Mixing mix bitwise operations and strings will not improve the performance and reduces the redubility of code.
Assuming that
bitIndexis 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):Online Demo
A quick recap on how XOR works.
That means zeros
0in the bit-mask1 << bitIndex, created by shifting the value of1by 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 into0, or if there would be0at the same position it would result into1.Example:
value = 7,index = 2value = 0,index = 0