Harshit Agrawal Harshit Agrawal - 1 month ago 5
C++ Question

c++: How to flip the binary values of each bit in int

Suppose I have an integer

int a


In c++, as this
int
uses 4 bytes(32 bits) of memory, all bits would be occupied by either
1
's or
0
's. So, I wish to flip the values of each bit. That is, wherever in each bit there is
1
convert it to
0
and
0
to
1
.

Is there an easy way to go about this?

Edit: I also want to play with boolean algebra also. That is if I can execute basic boolean operations like addition, subtraction, etc.

Answer

You're looking for the binary not operator (~).

So

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.

The wikipedia and the GNU C have plenty of information of these binary operators.

Comments