trying to find absolute value and i thought there was a simple way to just invert the sign with '~' or something.
views:
519answers:
7float newValue = oldValue * -1;
or
float newValue = -(oldValue); //() aren't needed, I just use them out of habit
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.
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.)
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!