He does something called type punning .
It should be remembered that floating point values ββare often stored in a completely different format than integer ones (most often the IEEE floating point format ), and the use of the union is to obtain a raw floating point format.
To be more specific, this happens:
- Assignment
conv.f = val[i] . This converts the integer in val[i] to a floating point value and stores it in conv.f - Assignment
val[i] = conv.i This gets the raw floating point bit pattern stored in the union and assigns it to val[i] .
This works because the union is not like a structure with individual members. In a union, all members have the same memory. Changing one member of the union will change all members.
A note about why the connection is used: this conversion could be done in other ways, but then it violates the rule of strict aliases , however, the use of unions for the punning type is allowed.
Some programmer dude
source share