Reputation: 21
Hello I am trying to understand how unions in C work. I have created a float called temperature with the number 12345678.
This converts to binary (25 bits): 101111000110000101001110
In the union I created called temp_union, I created a float variable (value2) and an integer array with 4 bytes called value1.
I then store the temperature into the union value2.
When I display value1[0], shouldn't this print the first 8 bits of the float number? And value[1] the next 8 bits, value[2] the next 8 bits and so on..
So displaying value1[0] as an integer, would be 78 (01001110)
Displaying value1[1] as an integer, would be 97 (01100001)
Displaying value1[2] as an integer, would be 188 (10111100)
Instead, I get the following:
value1[0]: 1262248270
value1[1]: 32766
value1[2]: 0
value1[3]: 0
My code is below:
#include <stdio.h>
int main()
{
float temperature = 12345678;
union union_data_type {
int value1[4];
float value2;
};
union union_data_type temp_union;
temp_union.value2 = temperature;
printf("\n Temperature float value: ");
printf("%f", temp_union.value2);
printf("\n Value 0: ");
printf("%i", temp_union.value1[0]);
printf("\n Value 1: ");
printf("%i", temp_union.value1[1]);
printf("\n Value 2: ");
printf("%i", temp_union.value1[2]);
printf("\n Value 3: ");
printf("%i", temp_union.value1[3]);
}
Upvotes: 0
Views: 262
Reputation: 12344
size of float usually is 32 bit, which is 4 bytes. 'int' is usually 4 bytes as well, so I assume that what you have.
So, in your case the union consists of a 4 bytes float and 16 bytes of int array. only first 4 bytes (value1[0]) of the array overlaps with the float member.
your union then looks like the following in memory
addr int value1[4] float value2
00000000 [0] 4 bytes 4 bytes
00000004 [1] 4 bytes ---
00000008 [2] 4 bytes ---
0000000C [3] 4 bytes ---
where addr here represents an offset from the stack location provided to you,
When you initialize the float, you also initialize value1[0]. The rest remains uninitialized and is just trash.
float
is usually represented by encoding defined in IEEE 754 standard (https://en.wikipedia.org/wiki/Single-precision_floating-point_format) and the bits of it are interepreted by the cpu and the print services. Same bits for int
are interpreted differently.
So, your result shows value1[0] which is an int
representation of the float
bits, and uninitialized values for other members of the array.
Upvotes: 0
Reputation: 276
When I display
value1[0]
, shouldn't this print the first 8 bits of the float number? Andvalue[1]
the next 8 bits,value[2]
the next 8 bits and so on..
No. An int
usually is 32bit long. So in your case with temp_union.value1[0]
you get the first 32 bit of your float value.
If you want to acces one byte at a time change your union to
union union_data_type {
uint8_t value1[4];
float value2;
};
For that you will have to #include <stdint.h>
.
But regarding your understanding of how a union works, you are correct.
Upvotes: 1