显示数字的位

Dysplaying the bits of a number

我创建了一个程序,它应该接收一个整数和 return 该数字的二进制表示。现在我想添加一个函数来计算数字中有多少个“1”,这就是我遇到麻烦的地方,例如:

输入:123 -> 0b01111011 -> 4(因为“1”附近有4个)

为此,我需要将当前脚本的输出存储在一个变量中,但我不能超出这个范围,因为我使用的是 putchar:

#include <stdio.h>

void displayBits(unsigned int value); // prototype

int main(void)
{ 
   unsigned int x; // variable to hold user input
   printf("%s", "Enter a nonnegative int: ");
   scanf("%u", &x);
   displayBits(x);
} 
// display bits of an unsigned int value
void displayBits(unsigned int value)
{  



   // define displayMask and left shift 31 bits
   unsigned int displayMask = 1 << 7; 
   printf("%10u = ", value);
   printf("0b");


   // loop through bits 
   for (unsigned int c = 1; c <= 8; ++c) {

      putchar(value & displayMask ? '1' : '0');
      value <<= 1;


   } 
   putchar('\n');
} 

如果您要计算设置为 1 的相邻位的最大数量,可以按如下方式进行。

有一个计数器可以跟踪您找到的一行中出现“1”位的可能性。当您找到“1”时递增它,当您找到“0”时将其设置为 0。您还需要一个跟踪最长 运行 的变量。如果当前大于最长的运行,设置最长的为当前的

int current_run = 0, longest_run = 0;
while (displayMask) {
   if (value & displayMask) {
       current_run++;
       if (current_run > longest_run) {
           longest_run = current_run;
       }
       putchar('1');
   } else {
       current_run = 0;
       putchar('0');
   }

   displayMask >>= 1;
}