How can I print C-bit by bit to see the low-level representation?

I want to know how a computer represents a type double

in a bit, but the bit &

and operators |

cannot use double

. And memcpy(&d, &src, 8)

it doesn't work either. Any suggestions?

+2


source to share


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


source


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.



http://en.wikipedia.org/wiki/IEEE_754-1985

+2


source


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


It won't be very helpful if you don't know a little about typical IEEE FP representations.

Chances are, the way your car represents doubles is spelled out here .

0


source


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


The key is to convert double

to long long

(assuming sizeof(double) == sizeof(long long)

) without changing the binary representation. This can be achieved in one of the following ways:

  • cast: double a; long long b = *((long long *)&a);

  • union: union { double a ; long long b };

0


source


Another option is to use bitfields . Armed with this structure and the knowledge of how the double should be stored on your computer, you can easily print out the various parts of the double's internal representation. It looks a bit like they're here .

0


source







All Articles