吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C语言如何计算浮点数中的设置位

C语言如何计算浮点数中的设置位

来源:网络 | 更新时间:2022-01-29 20:43:56
给定一个浮点数,编写一个函数来计算其二进制表示中的设置位。  例如,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

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com