On Floats and Integers - Answer

Previous | Home

Let's look at the code snippet once more.

int i = 10;
float *pf = (float *)&i;

cout<<"i : "<<i<<endl;
cout<<"*pf : "<<*pf<<endl;
Here, one might ask as to why a pointer to a float is being used instead of a straightforward float? Well the answer to that question is the answer to the riddle. The compiler treats integers and floats very differently. If we can find out how a given value is stored in memory as an integer or a float, it might give us a fair idea. The following program attempts precisely this.

#include <iostream.h>

void main()
{
	int i = 10;
	char *p;
	float f = 10;
	int c;

	cout<<"Byte-wise representation of integer 10\n";
	p = (char *)&i;

	for( c = 0 ; c < sizeof(i) ; ++c )
		cout<<(int)*p++<<endl;

	cout<<"\nByte-wise representation of float 10\n";
	p = (char *)&f;

	for( c = 0 ; c < sizeof(f) ; ++c )
		cout<<(int)*p++<<endl;
}

The Output

Byte-wise representation of integer 10
10
0
0
0

Byte-wise representation of float 10
0
0
32
65

As is evident from the output, integers and floats are stored in a completely diametric fashion. If we make an attempt to represent the float 10 as an integer what would result, as must be obvious is a very huge number. This is easily verified from the output of the following code snippet.

float f = 10;
int *pi = (int *)&f;
cout<<"*pi : "<<*pi<<endl;

The Output

*pi : 1092616192

This is exactly the kind of problem that type-casting solves. When you cast a value from a float to an integer (or from any other datatype to any other datatype), casting takes care of all the differences between the internal representations of the datatypes. Our program therefore would function flawlessly if we used straightforward integer and float objects instead of pointers.

int i = 10;
float f = i;	//no casting required for converting to a larger datatype
cout<<"i : "<<i<<endl;
cout<<"f : "<<f<<endl;

f = 20;
i = (int)f;
cout<<"\ni : "<<i<<endl;
cout<<"f : "<<f<<endl;

The Output

i : 10
f : 10

i : 20
f : 20

However, the question of exactly how floats and integers (or for our purposes just floats) are represented internally needs to be answered. I would have done it if I knew but I dont! If you do, I would really appreciate it if you could tell me. Please write to acheeriunni@yahoo.com. Thanx in advance :-).

Previous | Home 1