I want to invert a value of bit in digit. Function 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);
}
CodePudding user response:
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;
}
CodePudding user response:
How about:
String bin = Integer.toBinaryString( value );
char newChar = (char) (bin.charAt(bitIndex) ^ bin.charAt(bitIndex));
StringBuilder sb = new StringBuilder( bin );
sb.setCharAt( bitIndex, newChar );
return sb.toString();