How does this fabs () work?

The algorithm for finding the absolute value of the floating point number above is here . How it works?

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

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

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

Can someone break this and explain?

+4
source share
3 answers

The code is technically invalid C because it violates strict alias rules. However, if you tell your compiler not to abuse the alias rules, and you are guaranteed that double and int are laid out in memory, since they are on x86:

(int *)&x is a pointer to x . Appendix 1 moves the pointer forward 4 bytes. By dereferencing this, you get from the 4th to the 7th byte of double . You mask the high bit of this because it is the last double byte.

By the way, you can stop this due to anti-aliasing by using char * and adding 7 instead of 1. It is still terribly incapable.

+8
source

A double is 8 bytes wide and has the following format:

enter image description here

The code you cited assumes that int is 4 bytes wide and that int and double little-endian (the value of bits 0-7 is stored in byte 0, bits 8-15 in byte 1, etc.).

If x is a pointer to double :

 *(((int *) &x) + 0) addresses bits 0 through 31; *(((int *) &x) + 1) addresses bits 32 through 63. 

Thus, *(((int *) &x) + 1) &= 0x7fffffff sets bit 63 to zero, changing x to its absolute value.

+7
source

It depends on the platform.

Anyway, you have a double, where the most significant bit is the sign bit.

If your double has 8 bytes, and your int has 4 bytes, and you are in the LE system, the most significant bit is the most significant bit of the last byte or second integer.

So you take the second integer (you can also write ((int *)&x)[1] &= 0x7fffffff ) and clear its most significant bit.

+1
source

Source: https://habr.com/ru/post/1497920/


All Articles