I try to toggle the bits of a numeric value by using the ~
complement operator, but it results in a negative number. For example I want toggle 5 -> 2 (101 -> 010)
How can I change this number in Visual Studio?
I try to toggle the bits of a numeric value by using the ~
complement operator, but it results in a negative number. For example I want toggle 5 -> 2 (101 -> 010)
How can I change this number in Visual Studio?
What you want is the XOR operator ^
.
If your original number is x
, then:
int y = x ^ 0b111;
Will have the first 3 bits flipped (I supposed that's what you meant by "toggled").
As a 32-bit value, 5 is not 0b101. It is 0b0000'0000'0000'0000'0000'0000'0000'0101.
(Although those leading zeroes are not significant, value-wise, the fact that you are performing bit operations makes the "width" of the binary representation important.)
So, when you flip all the bits, you get 0b1111'1111'1111'1111'1111'1111'1111'1010 which is indeed a negative number per two's complement encoding.
If you just wanted to flip the three least significant bits, you can use a mask to do that:
const int y = x ^ 0b111;
This will leave all the other bits alone.
Hello you can do like this .
(~N)<0 ? (long)pow(2, 32) + ~N : ~N;