Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

We all know that the highest bit of an Int32 defines its sign. 1 indicates that it's negative and 0 that it's positive (possibly reversed). Can I convert a negative number to a positive one by changing its highest bit?

I tried to do that using the following code:

i |= Int32.MaxValue;

But it doesn't work.

like image 775
Domi.Zhang Avatar asked Oct 18 '11 15:10

Domi.Zhang


2 Answers

If you're talking about using bitwise operations, it won't work like that. I'm assuming you were thinking you'd flip the highest bit (the sign flag) to get the negative, but it won't work as you expect.

The number 6 is represented as 00000000 00000000 00000000 00000110 in a 32-bit signed integer. If you flip the highest bit (the signing bit) to 1, you'll get 10000000 00000000 00000000 00000110, which is -2147483642 in decimal. Not exactly what you expected, I should imagine. This is because negative numbers are stored in "negative logic", which means that 11111111 11111111 11111111 11111111 is -1.

If you flip every bit in a positive value x, you get -(x+1). For example:

00000000 00000000 00000000 00000110 = 6
11111111 11111111 11111111 11111001 = -7

You've still got to use an addition (or subtraction) to produce the correct result, though.

like image 59
Polynomial Avatar answered Sep 25 '22 17:09

Polynomial


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

like image 45
James Michael Hare Avatar answered Sep 23 '22 17:09

James Michael Hare