Invert bits in an integer in Java

-1

What is the best way to invert a bit of a whole number in Java? I have tried it in 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);
    
asked by Oundroni 19.05.2016 в 09:20
source

1 answer

5

The usual way to invert bits is to use the binary operator xor ( ^ ) along with the appropriate mask . In your case:

entero ^= 4
    
answered by 19.05.2016 / 09:34
source