Absolute value of a float

01: float myAbs(float x)
02: {
03:   // copy and re-interpret as 32 bit integer
04:   int casted = *(int*) &x;
05:   // clear highest bit
06:   casted &= 0x7FFFFFFF;
08:   // re-interpret as float
09:   return *(float*)&casted;
10: }

Explanation IEEE 754 floats' highest bit is the so-called sign bit: set to 1 for negative and 0 for positive numbers (incl. zero).
We just always set it to 0 − and we are done !

The data type "float" requires 32 bits. Unfortunately, C does not allow any bit operations on floats.
To work around this issue, these 32 bits are re-interpreted as a 32 bit integer (line 4).
Then clearing the sign bit becomes simple and easy (line 6), however, the required code looks a bit nasty.

The built-in C function fabs() is translated into its FABS intrinsic when the data value is already on the FPU stack.
When data is stored in main memory and will remain there after fabs, the above trick outperforms the FPU by far
because one FPU load and one store operation can be saved.
These FPU load/store can vastly skew the performance chart, so please be careful with interpreting the results.

Restrictions • designed for 32 bit IEEE floats

These ads
help me to pay
my server bills

Performance • constant time, data independent

+ Intel® Pentium™ D:
myAbs: ≈ 1 cycle per number
• fabs: ≈ 3 cycles per number (if on FPU stack)

+ Intel® Core™ 2:
myAbs: ≈ 1 cycle per number
• fabs: ≈ 1 cycle per number (if on FPU stack)

+ Intel® Core™ i7:
myAbs: ≈ 1 cycle per number
• fabs: ≈ 1 cycle per number (if on FPU stack)
Performance Chart
CPU cycles
(full optimization,
lower values are better)

Assembler Output
compiler: Visual C++ 2008
in: eax ← x
out: eax → result
01:   and eax, 7FFFFFFFh

compiler: Visual C++ 2008
in: ST(0) ← x
out: ST(0) → result
01:   fabs

Download The full source code including a test program is available for download.

References none

More Twiddled Bits
  1. Absolute value of a float
  2. Absolute value of an integer
  3. Approximative inverse of a float
  4. Bit manipulation basics
  5. Bit mask of lowest bit not set
  6. Count bits set in parallel a.k.a. Population Count
  7. Detects zero bytes inside a 32 bit integer
  8. Endianess
  9. Extend bit width
  10. Float inverse square root approximation
  11. Float square root approximation
  12. Is power of two
  13. Minimum / maximum of integers
  14. Parity
  15. Position of lowest bit set
  16. Round up to the next power of two
  17. Sign comparison
  18. Sign of a 32 bit integer
  19. Swap two values
Extra: Javascript bit manipulator

... or go to the index