G
Gary Baydo
In an effort to write a simple rounding function, I wrote the following code
out of
curiosity. My question is, can I rely on the output to 'make sense'? As an
added
'exercise' I tried to write the code in a portable manner, not just for my
box that
uses 8-bit bytes and 4-byte floats.
Comments and critiques are welcome. Thanks.
/* display the binary representation of a float variable */
#include <stdio.h>
#include <limits.h>
int main(void) {
int i, j;
float f, *pf;
char *pc;
f = 42; /* assign some arbitrary value */
pf = &f;
pc = (char *)pf;
for (i = 0; i < sizeof(float); i++) {
for (j = 0; j < CHAR_BIT; j++) {
printf("%d", *pc & (1 << j) ? 1 : 0);
fflush(stdout);
}
pc++;
printf(" ");
fflush(stdout);
}
return 0;
}
out of
curiosity. My question is, can I rely on the output to 'make sense'? As an
added
'exercise' I tried to write the code in a portable manner, not just for my
box that
uses 8-bit bytes and 4-byte floats.
Comments and critiques are welcome. Thanks.
/* display the binary representation of a float variable */
#include <stdio.h>
#include <limits.h>
int main(void) {
int i, j;
float f, *pf;
char *pc;
f = 42; /* assign some arbitrary value */
pf = &f;
pc = (char *)pf;
for (i = 0; i < sizeof(float); i++) {
for (j = 0; j < CHAR_BIT; j++) {
printf("%d", *pc & (1 << j) ? 1 : 0);
fflush(stdout);
}
pc++;
printf(" ");
fflush(stdout);
}
return 0;
}