How to get the bits of a float value in C

2 Answers

0 votes
#include <stdio.h>

union FloatBits {
    float f;
    unsigned int ui;
};

int main() {
    union FloatBits fbits;
    fbits.f = 3.14f; // 01000000_01001000_11110101_11000011    
    
    for (int i = sizeof(unsigned int) * 8 - 1; i >= 0; i--) {
        putchar((fbits.ui & (1u << i)) ? '1' : '0');
    }
    
    return 0;
}


// https://www.h-schmidt.net/FloatConverter/IEEE754.html



/*
run:

01000000010010001111010111000011    

*/

  

 



answered May 22, 2024 by avibootz
edited May 22, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

int getBit(int a, int location) {
    int result = a & 1 << location;

    if (result == 0) {
        return 0;
    }
    
    return 1;
}

int main()
{
    // 1 sign bit | 8 exponent bit | 23 fraction bits
    // 0            10000000         10010001111010111000011

    float f = 3.14f; // 01000000_01001000_11110101_11000011    
    int* n = &f;

    for (int i = 31; i >= 0; i--) {
        printf("%d", getBit(*n, i));
    }

    return 0;
}


// https://www.h-schmidt.net/FloatConverter/IEEE754.html



/*
run:

01000000010010001111010111000011

*/

 



answered May 22, 2024 by avibootz
edited May 22, 2024 by avibootz

Related questions

1 answer 158 views
1 answer 108 views
1 answer 95 views
95 views asked Sep 3, 2023 by avibootz
1 answer 107 views
107 views asked Feb 11, 2023 by avibootz
1 answer 130 views
130 views asked Jan 23, 2023 by avibootz
1 answer 135 views
...