#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;
}
#include<stdio.h> #include<iostream.h> main() { unsigned char c,i; union temp { float f; char c[4];
Share
Bitwise Operation in your code
c = 128therefore the binary representation isa & cwill and every ith but ifcwith evert ith bit ofa. Becauseconly has1in the MSB position (pos 7), soa & cwill be non-zero ifahas a1in its position 7 bit, ifahas a0in pos bit, thena & cwill be zero. This logic is used in theifblock above. Theifblock is entered depending upon if the MSB (position 7 bit) of the byte is 1 or not.Suppose
a = ? ? ? ? ? ? ? ?where a?is either0or1Then
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
cis shifted left one position, so the1in thecpropagates left wise. So in each iteration masking with the other variable you are able to know if there is a1or a0at that position of the variable.Use in your code
You have
Inside the union the
floatand thechar c[4]share the same memory location (as the property of union).Now,
sizeof (f) = 4bytes)You assignk.f = 5345341or whatever . When you access the arrayk.arr[0]it will access the 0th byte of the floatf, when you dok.arr[1]it access the 1st byte of the floatf. 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)Or the byte ordering could be reversed
Your code loops on this and shifts the
cwhich propagates the only1in thecfrom 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 variablef, 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.