0

我知道网上有很多关于如何从字符串转换为十六进制的教程。好吧,我有一个问题。

我的代码(见下文)最多可使用 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;
}
4

2 回答 2

1

A long can't store more than 32 bits (actually 31 plus a sign bit). Try a long long int and strtoll() if you want more than 32 bits, or unsigned long and strtoul() if 32 is enough.

于 2013-10-03T08:56:49.693 回答
1

This probably happens because the long is 32 bits on your machine and a signed long can't hold 32 bits in 2's complement. You could try to use an unisgned (which doesn't "waste" a bit for the sign) or a long long which is 64 bits wide.

unsigned long x = strtoul(InputString, &pEnd, Base);
                    ^^^^

Or long long:

long long x = strtoll(InputString, &pEnd, Base);

The functions strtol and strtoul have been available for a long time in C++. Indeed strtoll and long long have been introduced in C++11.

于 2013-10-03T08:57:47.437 回答