I have this integer int nine = 9;
which in binary is 1001
. Is there an easy way to invert it so I can get 0110
?
Here we use the flip() of bitset to invert the bits of the number, in order to avoid flipping the leading zeroes in the binary representation of the number, we have calculated the number of bits in the binary representation and flipped only the actual bits of the number.
You're looking for the binary not operator (~). int a = 0x04; int b = ~a; the value of b is 1111 1111 1111 1011 while the value of a is 0000 0000 0000 0100.
Ways for flipping binary bitsUsing Loops: By iterating each and every bit we check if the bit is 1 if true we change the bit 1 to bit 0 and vice-versa. Using replace() method: In Python, strings have an in-built function replace, which replaces the existing character with a new character.
The java. lang. Integer. reverse() method returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified int value.
int notnine = ~nine;
If you're worried about only the last byte:
int notnine = ~nine & 0x000000FF;
And if you're only interested in the last nibble:
int notnine = ~nine & 0x0000000F;
The ~ operator is the bitwise negation, while the mask gives you only the byte/nibble you care about.
If you truly are interested in only the last nibble, the most simple is:
int notnine = 15 - nine;
Works for every nibble. :-)
There's an operator specifically for it, ~
.
nine = ~nine;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With