How are floating points represented and interpreted by a compiler. I am trying to understand that so I can easily interpret what byte array would mean for floats and doubles.
Thanks
How are floating points represented and interpreted by a compiler. I am trying to understand that so I can easily interpret what byte array would mean for floats and doubles.
Thanks
Try this link: http://en.wikipedia.org/wiki/IEEE_754
I just found that this might be a little more helpful: http://en.wikipedia.org/wiki/IEEE_754-1985
This is the IEEE-Standard for floating point numbers. There is one from 1985 and a revised edition from 2008. Float is 32bit, double is 64bit (explained in the second link).
Edit: Thx to the comment by Don, here's the link to Intels 80bit floating point description: http://en.wikipedia.org/wiki/Extended_precision
It might also be worth noting that there is a static bool const
member of std::numeric_limits
, is_iec559
, which is naturally only available for floating point types. The name is pretty self explanatory...
To actually interpret it you would probably not want to treat it as bytes anyway because mantisa boundries don't align to an 8bit boundry.
Something along the lines of:
mantisa = (*(unsigned int *)&floatVal) | MANTISA_MASK;
exp = ((*(unsigned int *)&floatVal) | EXP_MASK ) >> EXP_SHIFT;
sign = ((*(unsigned int *)&floatVal) | SIGN_MASK ) >> SIGN_SHIFT;
Would let you pull it apart to play with the juice center.
EDIT:
#include <stdio.h>
void main()
{
float a = 4;
unsigned int exp,sign,mantisa;
int i;
for(i = 0;i<4;i++)
{
exp = (*((unsigned int *)&a) >>23) & 0xFF;
sign = (*((unsigned int *)&a) >>31) & 0x01;
mantisa = (*((unsigned int *)&a)) & 0x7FFFFF | 0x800000;
printf("a = %04x\r\n",*((unsigned int *)&a));
printf("a = %f\r\n",a);
printf("exp = %i, %02x\r\n",exp,exp);
printf("sign = %i, %02x\r\n",sign,sign);
printf("mantisa = %i, %02x\r\n\r\n",mantisa,mantisa);
a = -a / 2;
}
}
Produces:
a = 40800000
a = 4.000000
exp = 129, 81
sign = 0, 00
mantisa = 8388608, 800000
a = c0000000
a = -2.000000
exp = 128, 80
sign = 1, 01
mantisa = 8388608, 800000
a = 3f800000
a = 1.000000
exp = 127, 7f
sign = 0, 00
mantisa = 8388608, 800000
a = bf000000
a = -0.500000
exp = 126, 7e
sign = 1, 01
mantisa = 8388608, 800000
Press any key to continue . . .