How to count set bits in a floating point number in C?

In this problem, one floating point value is given. We have to find the number of set bits in the binary representation of it. This involves analyzing the IEEE 754 single-precision floating point format used by C compilers.

For example, if a floating point number is 0.15625, there are six set bits in its 32-bit binary representation. The IEEE 754 format consists of 1 sign bit, 8 exponent bits, and 23 mantissa bits.

IEEE 754 Single Precision Format (32 bits) S Sign 1 bit Exponent 8 bits (Biased by 127) Mantissa (Fraction) 23 bits (Implicit leading 1) 31 30-23 22-0

Syntax

int count_float_set_bit(float x);

Approach

To count set bits in a floating point number, we need to access its binary representation byte by byte. We cast the float's address to a char pointer and process each byte individually −

Example

#include <stdio.h>

int char_set_bit_count(char number) {
    unsigned int count = 0;
    while (number != 0) {
        number &= (number-1);  // Clear the lowest set bit
        count++;
    }
    return count;
}

int count_float_set_bit(float x) {
    unsigned int n = sizeof(float)/sizeof(char); // Number of bytes in float
    int i;
    char *ptr = (char *)&x; // Cast address to char pointer
    int count = 0;
    
    for (i = 0; i < n; i++) {
        count += char_set_bit_count(*ptr); // Count bits for each byte
        ptr++;
    }
    return count;
}

int main() {
    float x = 0.15625;
    printf("Binary representation of %f has %d set bits
", x, count_float_set_bit(x)); // Test with another value float y = 1.5; printf("Binary representation of %f has %d set bits
", y, count_float_set_bit(y)); return 0; }
Binary representation of 0.156250 has 6 set bits
Binary representation of 1.500000 has 9 set bits

How It Works

  • The char_set_bit_count() function uses Brian Kernighan's algorithm to count set bits efficiently
  • The expression number &= (number-1) clears the lowest set bit in each iteration
  • We cast the float's address to char* to access its byte-level representation
  • Each byte is processed separately to count all set bits in the 32-bit float

Conclusion

Counting set bits in a floating point number requires byte-level access to the IEEE 754 representation. This technique is useful for understanding how floating point numbers are stored internally in memory.

Updated on: 2026-03-15T10:36:52+05:30

580 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements