Manish Kumar
Manish Kumar

Reputation: 1469

typecasting long to float using gcc libraries

I am running a simple programme on Cnetos 6.2.0 version 64 bit machine.

int main()
{

int b = 1078085270;//1078085218;
float a;
a = (float)(b);

printf("val of a  is %f\n",a);

return 0;
}

The output of a is 1078085248. I changed the value to 1078085218. still got the same result. I am not able to understand why or how the output gets corrupted or changed ?

Can anyone explain please ?

Upvotes: 2

Views: 165

Answers (1)

Stephen Canon
Stephen Canon

Reputation: 106167

Look at the number 1078085270 in binary:

b1000000010000100100011010010110

An IEEE-754 single-precision float has only 24 bits of precision, but this number has more than 24 significant bits, so when you cast this number to float, it must be rounded. The two closest numbers representable in float are:

b100000001000010010001101 0000000
b100000001000010010001110 0000000

(the spaces indicate the break between the 24th and 25th digits, the point at which the number is rounded). Because your number is closer to the first number, it is rounded to that value, which is 1078085248 in decimal.

Upvotes: 4

Related Questions