C++从二进制转换为十进制数

Translation from binary into decimal numbers in C++

本文关键字:十进制数 转换 二进制 C++      更新时间:2023-10-16

我试图构建一个函数,将存储在字符串中的二进制数计算成存储在long long中的十进制数。我认为我的代码应该可以工作,但它没有。

在此示例中,对于二进制数101110111十进制数为375。但我的输出完全令人困惑。

这是我的代码:

#include <string>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string.h>
int main() {
std::string stringNumber = "101110111";
const char *array = stringNumber.c_str();
int subtrahend = 1;
int potency = 0;
long long result = 0;
for(int i = 0; i < strlen(array); i++) {
result += pow(array[strlen(array) - subtrahend] * 2, potency);
subtrahend++;
potency++;
std::cout << result << std::endl;
}
}

这是输出:

1
99
9703
894439
93131255
9132339223
894974720087
76039722530902
8583669948348758

我在这里做错了什么?

'1' != 1

如@churill的评论中所述。'1' == 49.如果您在 linux 上,请在终端中键入man ascii以获取 ascii 表。

试试这个,它是相同的代码。我只是直接使用stringNumber,而不是使用它const char*。我从当前索引中减去了'0''0' == 48,所以如果你减去它,你会得到实际的10整数值:

auto sz = stringNumber.size();
for(int i = 0; i < sz; i++) {
result += pow((stringNumber[sz - subtrahend] - '0') * 2, potency);
subtrahend++;
potency++;
std::cout << result << std::endl;
}

此外,使用std::string提供的方法,例如.size(),而不是在每次迭代时都执行strlen()。快多了。


在生产环境中,我强烈建议使用std::bitset而不是推出自己的解决方案:

std::string stringNumber = "1111";
std::bitset<64> bits(stringNumber);
bits.to_ulong();

你忘了把你的数字转换成整数。另外,您真的不需要使用C字符串。

这是代码的更好版本

int main() {
std::string stringNumber = "101110111";
int subtrahend = 1;
int potency = 0;
long long result = 0;
for(int i = 0; i < stringNumber.size(); i++) {
result += pow(2*(stringNumber[stringNumber.size() - subtrahend] - '0'), potency);
subtrahend++;
potency++;
std::cout << result << std::endl;
}
}

从字符串数字中减去'0'会将数字转换为整数。

现在为了额外的信用,写一个不使用pow的版本(提示:potency *= 2;而不是potency++;(

C++ 方式

#include <string>
#include <math.h>
#include <iostream>

using namespace std;
int main() {
std::string stringNumber = "101110111";   
long long result = 0;
uint string_length = stringNumber.length();
for(int i = 0; i <string_length; i++) {
if(stringNumber[i]=='1')
{
long pose_value = pow(2, string_length-1-i);        
result += pose_value;
}       

}
std::cout << result << std::endl;
}