Difficult subject. A direct way to change the sign to a floating point number is to flip the value of the most significant bit of the variable. The notations listed in the other answers are at the mercy of the compiler, which is usually good, but not always. For "float x" the answer is:
*(unsigned int*)&x ^= (1<<31)
If you're writing something like an iPhone that has a Cortex A8 processor (or something like that), you want to avoid duplication, and also avoid conventions when working with floats in internal loops. So you can do this:
*(unsigned int*)&x ^= ( (x<0) << 31 );
Which will turn negatives into positives without using a jump instruction. If it is in the inner loop, it will be 5-20 times faster than using another method on the iPhone. If this is not in the inner loop, then you probably care!
Jpn
source share