Given a floating point number, write a function to count set bits in its binary representation.
For example, floating point representation of 0.15625 has 6 set bits (See this). A typical C compiler uses single precision floating point format.
We can use the idea discussed here. The idea is to take address of the given floating point number in a pointer variable, typecast the pointer to char * type and process individual bytes one by one. We can easily count set bits in a char using the techniques discussed here.
Following is C implementation of the above idea.
C
#include <stdio.h>
unsigned int countSetBitsChar( char n)
{
unsigned int count = 0;
while (n)
{
n &= (n-1);
count++;
}
return count;
}
unsigned int countSetBitsFloat( float x)
{
unsigned int n = sizeof ( float )/ sizeof ( char );
char *ptr = ( char *)&x;
int count = 0;
for ( int i = 0; i < n; i++)
{
count += countSetBitsChar(*ptr);
ptr++;
}
return count;
}
int main()
{
float x = 0.15625;
printf ( "Binary representation of %f has %u set bits " , x,
countSetBitsFloat(x));
return 0;
}
|
Output:
Binary representation of 0.156250 has 6 set bits
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
21 Jun, 2022
Like Article
Save Article