C++从二进制转换为十进制数
Translation from binary into decimal numbers in C++
我试图构建一个函数,将存储在字符串中的二进制数计算成存储在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
,所以如果你减去它,你会得到实际的1
或0
整数值:
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;
}
相关文章:
- visual在c++中将十进制数转换为二进制数
- C++从二进制转换为十进制数
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 将分数转换为十进制数并对其进行排序
- 如何使用链表将负十进制数转换为二进制?
- 以C++格式将十六进制字符串转换为十进制数
- 将大十六进制数转换为十进制形式(以 10 为基数的形式)的算法
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- 将字节数组转换为 C++ 中的十进制数
- 您能否给我一个 16 位(或更多)十进制数,该十进制数仅在第 15 位正确转换为双精度浮点圆
- 使用堆栈将十进制数转换为二进制数
- 将浮点数转换为字符串,并指定精度和十进制数字数?
- 如何将字符数转换为十进制并返回或转换ASCII'A'-'Z'/'a'-'
- 将十进制数转换为包装 BCD,反之亦然
- 转换字符串十进制数时的精度
- C++Cout将字符串转换为保留所有小数的十进制数
- 将十进制数转换为二进制时出现意外结果
- 一个从x数制到十进制的转换器
- 将二进制向量转换为十进制数组