0

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?

Matze
  • 5,100
  • 6
  • 46
  • 69
방진영
  • 21
  • 4

5 Answers5

1

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

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
0

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

I prefer this:

number ^= 1UL << N
wair92
  • 446
  • 11
  • 24
0

Thank you I solve this problem.

By Use number ^= 1UL << N Thank you for your Answer.

방진영
  • 21
  • 4
-2

Hello you can do like this .

(~N)<0 ? (long)pow(2, 32) + ~N : ~N;