我知道网上有大量关于如何将字符串转换为十六进制的教程。好吧,我对此有疑问。
我的代码(见下文)最多可处理 31 个字符,我终究无法弄清楚原因。每当有 32 个字符时,它最多只能达到 7fffffff。
我需要能够输入类似“111111111100000000001010101000”的内容
应该很容易修复,只是不确定在哪里
我的尝试(可编译):
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int Base = 2;
long x;
char InputString[40];
char *pEnd = NULL; // Required for strtol()
cout << "Number? ";
cin >> InputString;
x = strtol(InputString, &pEnd, Base); // String to long
cout << hex << x << endl;
return 4;
}
最佳答案
这可能是因为 long 在您的机器上是 32 位,而 signed long
不能在 2 的补码中保存 32 位。您可以尝试使用 unisgned
(不会“浪费”一点符号)或 64 位宽的 long long
。
unsigned long x = strtoul(InputString, &pEnd, Base);
^^^^
或者long long
:
long long x = strtoll(InputString, &pEnd, Base);
函数strtol
和 strtoul
在 C++ 中已经可用了很长时间。事实上,strtoll
和 long long
已经在 C++11 中被引入。
关于c++ - 如何将 32 个字符的二进制字符串转换为十六进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19154820/