What is the best way to reverse a bit of an integer in Java? I have tried the following way although it seems inelegant to me:
int entero = 4+2+1;
if ((entero & 4) == 4)
entero -= 4;
else
entero += 4;
System.out.println ("Entero con el bit 3 invertido: " + entero);
The usual way to invert bits is by using the binary operator xor (
^
) together with the appropriate mask . In your case: