计算二进制文件中的位数
Count the number of digits in a Binary
对于这个程序,我将输入一个二进制数,它将转换为十进制数。最后,我想返回我输入的二进制数中的位数。例如,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
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 编译多个C++文件.调用二进制文件以运行代码
- 如何使用位字段将数据从二进制文件复制到结构中?
- uint8_t同一二进制文件的不同十进制值
- C++单个生成文件多个二进制文件
- 计算二进制文件中的位数
- 在 64 位 Linux armv8 计算机上编译 32 位二进制文件时遇到问题
- Wxwidgets 在另一台计算机上运行二进制文件时出现问题
- 计算 c# 中二进制文件符号的频率不起作用,但适用于等效的 c++ 代码
- 是否可以在为Solaris SPARC生成二进制文件的英特尔计算机上编写QT C++项目