我是编程新手,正在尝试理解以下程序。
该程序获取将整数存储为数字所需的最小位数。
#include <stdio.h>
/*function declaration
* name : countBit
* Desc : to get bits to store an int number
* Parameter : int
* return : int
*/
int countBit(int);
int main()
{
int num;
printf("Enter an integer number :");
scanf("%d",&num);
printf("Total number of bits required = %d\n",countBit(num));
return 0;
}
int countBit(int n)
{
int count=0,i;
if(n==0) return 0;
for(i=0; i< 32; i++)
{
if( (1 << i) & n)
count=i;
}
return ++count;
}
您能解释一下 if( (1 << i) & n)
是如何实现的吗?条件有效吗?
最佳答案
首先,您应该阅读 Bitwise Operators .
<小时/>for(i=0; i< 32; i++)
{
// Check if the bit at position i is set to 1
if( (1 << i) & n)
count=i;
}
用简单的英语来说,这是检查所有“设置”位的最高位置是什么。
This program gets the minimum number of bits needed to store an integer as a number.
获取最大“设置”位的位置将告诉我们需要多少位来存储该数字。如果我们使用较少的位数,那么我们会将最大可能数量减少到低于我们所需的整数。
关于C 程序查找给定数字所需的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51309276/