1

I'm trying to print the a number stored in floating point in C and I'm struggling how to print it out. I'm doing this right now which prints the number in IEEE format. I want it printed in reverse straight from memory. How can I fix it? Thanks

void printbits(size_t n, void *c) {
    unsigned char *t = c; 
    if (c == NULL) 
        return; 
    while (n > 0) { 
        int q; 
        --n;
        for(q = 0x80; q; q >>= 1) 
            printf("%x", !!(t[n] & q));
        } 
}
karan1525
  • 19
  • 2
  • 1
    Possible duplicate of [How do I display the binary representation of a float or double?](https://stackoverflow.com/questions/397692/how-do-i-display-the-binary-representation-of-a-float-or-double) – MFisherKDX Oct 30 '17 at 00:16

1 Answers1

1

Use a union:

union u {
    float f;
    unsigned char p[4];
}

Then u.f = myfloat; and iterate on u.p

MFisherKDX
  • 2,840
  • 3
  • 14
  • 25
  • @MFisherKDX, note that the size of a char may vary in c, also using two members of the union is undefined behaviour in the ANSI c standard – user3076936 Oct 30 '17 at 13:43
  • @user3076936 Hmm ... I thought sizeof(char) was guaranteed to be 1. – MFisherKDX Oct 30 '17 at 14:29
  • @MFisherKDX you are correct, sizeof(char) is guaranteed to be 1 as sizeof returns the size of an object in chars, it does not however guarantee that a char has 8 bits – user3076936 Oct 30 '17 at 14:36
  • @user3076936 So we this this pattern all the time. Is this wrong? `unsigned char c = (x >> 8)&0xff` – MFisherKDX Oct 30 '17 at 15:00
  • @MFisherKDX yes, in ANSI c it would be more correctly: unsigned char c = (x >> CHAR_BIT) &((char)(-1)); – user3076936 Oct 30 '17 at 15:09