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.
Answers (2)
Here is an example of bitwise NOT operator:
#include <iostream>
int main()
{
int a = 0;
int x = ~a;
unsigned int y = ~a;
std::cout << x << '\n';
std::cout << y << '\n';
}
Output:
-1
4294967295
For more information about binary operators and more try here
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.