How can I print C-bit by bit to see the low-level representation?
7 replies
Here:
#include <stdio.h>
int main ()
{
double decker = 1.0;
unsigned char * desmond = (unsigned char *) & decker;
int i;
for (i = 0; i < sizeof (double); i++) {
printf ("%02X ", desmond[i]);
}
printf ("\n");
return 0;
}
You can try: http://codepad.org/onHnAcnC
+6
user181548
source
to share
union {
double d;
unsigned char c[sizeof(double)];
} d;
int main(int ac, char **av) {
int i;
char s1[80], s2[80];
d.d = 1.0;
for(i = 0; i < sizeof d; ++i) {
sprintf(s1 + i * 3, " %02x", d.c[i]);
sprintf(s2 + i * 3, " %02x", d.c[sizeof d - 1 - i]);
}
printf("%s\n%s\n", s1, s2);
return 0;
}
$ ./a.out
00 00 00 00 00 00 f0 3f
3f f0 00 00 00 00 00 00
Or you could just read about the IEEE 754 standard that specifies the view.
+2
source to share
Separate bit arrangement by itself doesn't make sense. Suppose I have the following:1101
Perhaps I am saying it is unsigned and represents the value 13.
Maybe it's signed and this high bit means the value is negative, which means it's now -5.
Consider further that I believe the high two bits are the base and the low two bits are the exponent, then I get the value 3.
You see, this is not a repository, its interpretation. Read how floating point values are represented and interpreted; it will serve you much better than seeing how the bits are packed.
+1
source to share
This works for me
#include <stdio.h>
#include <string.h> /* memmove */
int main(void) {
unsigned char dontdothis[sizeof (double)];
double x = 62.42;
printf("%f\n", x);
memmove(&dontdothis, &x, sizeof dontdothis);
/* examine/change the array dontdothis */
dontdothis[sizeof x - 1] ^= 0x80;
/* examine/change the array dontdothis */
memmove(&x, &dontdothis, sizeof dontdothis);
printf("%f\n", x);
return 0;
}
Result
62.420000
-62.420000
0
source to share