C 程序查找给定数字所需的位数

标签 c

我是编程新手,正在尝试理解以下程序。

该程序获取将整数存储为数字所需的最小位数。

#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/

相关文章:

c - 为什么在编辑器中打开文件时看不到结构插入记录?

c - GCC: 'multiple definition' gcc 4.8 版本问题

c - 当我们在 C 中将两个指针等式化时会发生什么?

objective-c - 结构内存分配(泄漏和崩溃,iPhone 上的分析)

java - 如何使用 Win32 API 直接从驱动器读取/写入驱动器

c - C 中是否有相当于 python help() 的功能?

c++ - 浮点异常错误

c - 二进制序列检测器

c - 有没有办法在 C 中获取数组中的元素数?

c - 确定函数原型(prototype)