ben wrote:
> i'm learning about the floating point format that's used on my computer
> (apple mac so powerpc)
>
> i've written a function to print out the bits in a float to see how
> floats are represented and i also have a software programmer's
> calculator called BinCalc which shows the bits of whatever number.
>
> the bits that my code and the bits that the calculator show, for the
> same value, don't match.
/* There is no reason to suppose that your calculator and your Apple
* have the same representation for floating point numbers. Try the
* following code out. Note that the output of my implementation is
* very different from what you report. */
#include <stdio.h>
#include <string.h>
#define showhex(x, s)\
{\
unsigned char c[sizeof x];\
size_t i;\
memcpy(c,&x,sizeof x);\
printf("%Lg (%s, size = %lu) as hex: \n%4s",\
(long double)x, s, \
(unsigned long) sizeof x, "");\
for (i = 0; i < sizeof x; i++)\
printf("%02x ", c[i]);\
printf("\n");\
}
int main(void)
{
long double xl;
double x;
float xf;
xf = x = xl = 1.0;
printf("[Output for this implementation]\n\n");
printf("For 1.0, Ben's program would yield in hex: "
"BF 00 00 80\n" "and his calculator: 3F 00 00 80\n");
showhex(xf, "float");
showhex(x, "double");
showhex(xl, "long double");
xf = x = xl = 1.6;
printf("\nFor 1.6, Ben's program would yield in hex: "
"BF CD CC CC\n" "and his calculator: 3F CC CC CD\n");
showhex(xf, "float");
showhex(x, "double");
showhex(xl, "long double");
return 0;
}
[Output for this implementation]
For 1.0, Ben's program would yield in hex: BF 00 00 80
and his calculator: 3F 00 00 80
1 (float, size = 4) as hex:
00 00 80 3f
1 (double, size =

as hex:
00 00 00 00 00 00 f0 3f
1 (long double, size = 12) as hex:
00 00 00 00 00 00 00 80 ff 3f 00 00
For 1.6, Ben's program would yield in hex: BF CD CC CC
and his calculator: 3F CC CC CD
1.6 (float, size = 4) as hex:
cd cc cc 3f
1.6 (double, size =

as hex:
9a 99 99 99 99 99 f9 3f
1.6 (long double, size = 12) as hex:
00 d0 cc cc cc cc cc cc ff 3f 00 00
--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson