Tutorial :isn't there an operator in c to change the sign of a int float etc from negative to positive or vice versa?


trying to find absolute value and i thought there was a simple way to just invert the sign with '~' or something.


float newValue = oldValue * -1;  


float newValue = -(oldValue); //() aren't needed, I just use them out of habit  


Simple negation with - works, but most of the answers have ignored the fact that the OP is trying to do absolute value. For that, the correct tool is abs() for integers and fabs() for floats. The code will be crystal clear and the result will be what you expect. (Edit: Be sure to read the documentation and bugs for these tools. As Nick points out, negating the most negative number with abs() returns the same negative number.)


To invert the sign, put a minus in front of it.


The unary negation operator -(expr) does exactly what you want.

int x = -7;  int y = 7;  x = -x; // x is now 7  y = -y; // y is now -7  

The bitwise complement operator ~(expr) that you mention, on the other hand, flips all of the bits in the input.

In case it helps, one issue that many absolute value implementations in the wild ignore is that negating the most negative value of a given fixed-size two's complement integer type will overflow.


-x will give you the sign-inverted value of x.


Tricky subject. The direct way to change the sign on a floating point number is to flip the value of the variable's most significant bit. The notation listed in the other answers is at the mercy of the compiler, which is usually fine, but not always. For "float x", the answer is:

*(unsigned int*)&x ^= (1<<31)

If you are writing for something like the iPhone, which has a Cortex A8 processor (or something like it), you want to avoid doubles and also avoid conditionals when working with floats in inner loops. So, you can do this:

*(unsigned int*)&x ^= ( (x<0) << 31 );

Which will turn negatives to positives without using a branch instruction. If this is in an inner loop, it will be 5 to 20 times faster than using another method, on the iPhone. If it's not in an inner loop, then you probably don't care too much!


x = 0 - x;

? or do I miss the point?


This is a crappy solution, not sure what happened here. See the answer below with abs() for the correct one.

Even though this is an old question, maybe this answer will help some of you out. I wanted to have a positive or negative value of a number based on another result (lets say a boolean mustBeNegative) the way I did this is:

int number = 7;  if(mustBeNegative)  {        number = number * 1;  }  else  {        number = number * -1;  }  

The number will be its positive or negative value based on the "mustBeNegative" value. When number was already a negative number it will become positive and visa versa.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »