计算二进制文件中的位数

Count the number of digits in a Binary

本文关键字:二进制文件 计算      更新时间:2023-10-16

对于这个程序,我将输入一个二进制数,它将转换为十进制数。最后,我想返回我输入的二进制数中的位数。例如,1001 - 4 个二进制数字。二进制数的数字输出始终为 0。我应该使用size_type来做到这一点吗?

#include<iostream>
#include<string>
#include<bitset>
#include<limits>
#include<algorithm>
using namespace std;
int multiply(int x);
int multiply(int x)
{
if (x == 0)
{
return 1;
}
if (x == 1)
{
return 2;
}
else
{
return 2 * multiply(x - 1);
}
}
int count_set_bit(int n) 
{
int count = 0;
while (n != 0) 
{
if (n & 1 == 1) 
{
count++;
}
n = n >> 1; 
}
return count;
}
int main()
{
string binary;
cout << "ntDualzahlen : ";
cin >> binary;
reverse(binary.begin(), binary.end());
int sum = 0;
int size = binary.size();
for (int x = 0; x < size; x++)
{
if (binary[x] == '1')
{
sum = sum + multiply(x);
}
}
cout << "tDezimal : " << sum << endl;
int n{};
cout << "tAnzahl der Stelle : " << count_set_bit(n) << endl;
}

看起来您走在无符号整数的正确轨道上。 乘法中的有符号整数通常转换为带有保存结果符号的正整数。

您可以使用位数据解决方案节省一些时间,因为值测试不是免费的,而且"and"没有进位延迟。 当然,有些 CPU 的 ++ 速度比 += 1 快,但希望编译器知道如何使用它:

int bits( unsigned long num ){
retVal = 0 ;
while ( num ){
retVal += ( num & 1 );
num >>= 1 ;
}
return retVal ;
}

我记得 H-4201 一次乘以 2 位,也许使用 shift,也许加,也许携带/借用,所以 0 是不加,1 是加,2 是移位和加法,3 是携带/借用加法 (4 - 1(! 那是在IC倍增被埋没在电路和ROM中之前。 :D