How to convert negative number to positive by |= Operator in C#?

Why don't you just use the Math.Abs(yourInt) method? I don't see the necessity to use bitwise operations here.


The most-significant bit defines it's sign, true. But that's not everything:

To convert a positive number to a negative one, you have to:

  1. Negate the number (for example, +1, which is 0000 0001 in binary, turns into 1111 1110)
  2. Add 1 (1111 1110 turns into 1111 1111, which is -1)

That process is known as Two's complement.

Inverting the process is equally simple:

  1. Substract 1 (for example, -1, 1111 1111 turns into 1111 1110)
  2. Negate the number (1111 1110 turns into 0000 0001, which is +1 again).

As you can see, this operation is impossible to implement using the binary or-operator. You need the bitwise-not and add/substract.

The above examples use 8-bit integers, but the process works exactly the same for all integers. Floating-point numbers, however, use only a sign bit.


If you are just looking for a bitwise way to do this (like an interview question, etc), you need to negate the number (bitwise) and add 1:

int x = -13;
int positiveX = ~x + 1;

This will flip the sign if it's positive or negative. As a small caveat, this will NOT work if x is int.MinValue, though, since the negative range is one more than the positive range.

Of course, in real world code I'd just use Math.Abs() as already mentioned...

Tags:

C#