Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A way to invert the binary value of a integer variable

Tags:

c#

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 ?

like image 858
Martin Dzhonov Avatar asked Oct 31 '13 16:10

Martin Dzhonov


People also ask

How do you invert a binary number?

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.

How do you reverse a binary number in C++?

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.

How do you reverse a binary in Python?

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.

How do you flip a binary number in Java?

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.


2 Answers

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. :-)

like image 125
Scott Mermelstein Avatar answered Sep 23 '22 11:09

Scott Mermelstein


There's an operator specifically for it, ~.

nine = ~nine; 
like image 44
Servy Avatar answered Sep 22 '22 11:09

Servy