给定一个浮点数,编写一个函数来计算其二进制表示中的设置位。
例如,0.15625 的浮点表示有 6 个设置位。典型的 C 编译器使用单精度浮点格式。
我们可以使用这里讨论的想法。这个想法是在指针变量中获取给定浮点数的地址,将指针类型转换为 char * 类型并逐个处理各个字节。
以下是上述想法的 C 实现。
输出:
#include <stdio.h>
// A utility function to count set bits in a char.
// Refer http://goo.gl/eHF6Y8 for details of this function.
unsigned int countSetBitsChar(char n)
{
unsigned int count = 0;
while (n)
{
n &= (n-1);
count++;
}
return count;
}
// Returns set bits in binary representation of x
unsigned int countSetBitsFloat(float x)
{
// Count number of chars (or bytes) in binary representation of float
unsigned int n = sizeof(float)/sizeof(char);
// typecast address of x to a char pointer
char *ptr = (char *)&x;
int count = 0; // To store the result
for (int i = 0; i < n; i++)
{
count += countSetBitsChar(*ptr);
ptr++;
}
return count;
}
// Driver program to test above function
int main()
{
float x = 0.15625;
printf ("Binary representation of %f has %u set bits ", x,
countSetBitsFloat(x));
return 0;
}
Binary representation of 0.156250 has 6 set bits