Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this implementation of fabs() working?

The algorithm for finding the absolute value of a floating point number over here. How does this work?

//find absolute value
double x;
*(((int *) &x) + 1) &= 0x7fffffff;

I don't understand why the offset of 1 was necessary. It says:

the IA32 64-bit sign bit is 0x80000000 at an int address offset of +1.

Can someone break this down and explain?

like image 610
Anirudh Ramanathan Avatar asked Dec 04 '22 09:12

Anirudh Ramanathan


1 Answers

The code is technically invalid C as it breaks strict aliasing rules. However, if you tell your compiler not to abuse the aliasing rules and you're guaranteed that doubles and ints are laid out in memory as they are on an x86:

(int *)&x is a pointer to x. Adding 1 moves the pointer forward by 4 bytes. Dereferencing it gives you the 4th through 7th bytes of the double. You mask off the high bit of this because that is the last byte of the double.

Incidentally, you can stop this from being an aliasing violation by using a char * and adding 7 instead of 1. It's still horribly nonportable.

like image 124
tmyklebu Avatar answered Dec 24 '22 18:12

tmyklebu