Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of conversion is this code doing?

Tags:

c

unions

I ran across this code, where they are trying 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 am just not able to understand how this would work. The val[i] is assigned to conv.f and then the conv.i is used store back the value into val[i]. conv is a union type since we are using f, i will not have a valid value right?

Am I missing something here?

like image 470
bluefalcon Avatar asked Nov 06 '15 06:11

bluefalcon


People also ask

What is type conversion in coding?

In computer science, type conversion or typecasting refers to changing an entity of one datatype into another. There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion. Explicit type conversion in some specific way is known as casting.

What is type conversion with example?

In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another. An example would be the conversion of an integer value into a floating point value or its textual representation as a string, and vice versa.

Which of the following is a type of conversion?

Explanation: Basically 2 types of convsersion : Implicit Type Conversion and Explicit Type Conversion.


1 Answers

It's doing something called type punning.

The thing to remember here is that floating point values are often stored in a very different format than integers (most commonly IEEE floating point format), and the use of the union is to get the raw floating point format.

To be more specific, this is what happens:

  1. The assignment conv.f = val[i]. This converts the integer in val[i] to a floating point value, and stores it in conv.f.
  2. The 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 a union is not like a structure with separate members. In a union all members share the same memory. Modifying one member of the union will modify all members.


A note on why a union is used: This conversion could be made in other ways as well, but then that would break the strict aliasing rule, however using unions for type punning is allowed.

like image 139
Some programmer dude Avatar answered Oct 21 '22 05:10

Some programmer dude