What conversion does this code do?

I came across this code where they try to convert from float to int

int val[5]; union { int i; float f; } conv; ... val is updated with some value ... case OUT_FORMAT_FLOAT: for (i = 0; i < count; i++) { conv.f = val[i]; val[i] = conv.i; } 

But I just can't figure out how this will work. val[i] assigned to conv.f , and then conv.i used to store the value in val[i] . conv is a type of union, since we use f , i won't have the correct value right?

Did I miss something?

+8
c unions
source share
2 answers

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.

+5
source share

union allows you to store different types of data in one place. Space is allocated only for a member with a maximum sizeof(member) .

After the element f initialized, access to i can be obtained from this place.

0
source share

All Articles