#include<stdio.h>
#include<iostream.h>
main()
{
unsigned char c,i;
union temp
{
float f;
char c[4];
} k;
cin>>k.f;
c=128;
for(i=0;i<8;i++)
{
if(k.c[3] & c) cout<<'1';
else cout<<'0';
c=c>>1;
}
c=128;
cout<<'\n';
for(i=0;i<8;i++)
{
if(k.c[2] & c) cout<<'1';
else cout<<'0';
c=c>>1;
}
return 0;
}
c = 128
therefore the binary representation is
c = 10000000
a & c
will and every ith but if c
with evert ith bit of a
. Because c
only has 1
in the MSB position (pos 7), so a & c
will be non-zero if a
has a 1
in its position 7 bit, if a
has a 0
in pos bit, then a & c
will be zero. This logic is used in the if
block above. The if
block is entered depending upon if the MSB (position 7 bit) of the byte is 1 or not.
Suppose a = ? ? ? ? ? ? ? ?
where a ?
is either 0
or 1
Then
a = ? ? ? ? ? ? ? ?
AND & & & & & & & &
c = 1 0 0 0 0 0 0 0
---------------
? 0 0 0 0 0 0 0
As 0 & ? = 0
. So if the bit position 7 is 0 then answer is 0 is bit position 7 is 1 then answer is 1.
In each iteration c
is shifted left one position, so the 1
in the c
propagates left wise. So in each iteration masking with the other variable you are able to know if there is a 1
or a 0
at that position of the variable.
You have
union temp
{
float f;
char c[4];
} k;
Inside the union the float
and the char c[4]
share the same memory location (as the property of union).
Now, sizeof (f) = 4bytes)
You assign k.f = 5345341
or whatever . When you access the array k.arr[0]
it will access the 0th byte of the float f
, when you do k.arr[1]
it access the 1st byte of the float f
. The array is not empty as both the float and the array points the same memory location but access differently. This is actually a mechanism to access the 4 bytes of float bytewise.
NOTE THAT k.arr[0]
may address the last byte instead of 1st byte (as told above), this depends on the byte ordering of storage in memory (See little endian and big endian byte ordering for this)
Union k
+--------+--------+--------+--------+ --+
| arr[0] | arr[1] | arr[2] | arr[3] | |
+--------+--------+--------+--------+ |---> Shares same location (in little endian)
| float f | |
+-----------------------------------+ --+
Or the byte ordering could be reversed
Union k
+--------+--------+--------+--------+ --+
| arr[3] | arr[2] | arr[1] | arr[0] | |
+--------+--------+--------+--------+ |---> Shares same location (in big endian)
| float f | |
+-----------------------------------+ --+
Your code loops on this and shifts the c
which propagates the only 1
in the c
from bit 7 to bit 0 in one step at a time in each location, and the bitwise anding checks actually every bit position of the bytes of the float variable f
, and prints a 1 if it is 1 else 0.
If you print all the 4 bytes of the float, then you can see the IEEE 754 representation.