0

我正在将字符串从十六进制转换为十进制。问题是在 Visual Studio 编译器中,转换返回了错误的值。但是,当我在终端使用 g++ 编译器在 Mac 中编译相同的代码时,会正确返回值。

为什么会这样?

#include <string>
#include <iostream>
using namespace std;

int main()
{
    string hex = "412ce69800";

    unsigned long n = strtoul( hex.c_str(), nullptr, 16 ); 

    cout<<"The value to convert is: "<<hex<<" hex\n\n";
    cout<<"The converted value is: "<<n<<" dec\n\n";
    cout<<"The converted value should be: "<<"279926183936 dec\n\n";

    return 0;
}

输出:

输出文件

4

1 回答 1

2

因为在 Windowslong中是 32 位类型,不像大多数使用LP64 内存模型的Unix/Linux 实现,其中long64 位。该数字412ce69800有 39 位,本质上不能以 32 位类型存储。阅读编译器警告,您将立即知道问题所在

C 标准只要求long至少有 32 位。C99 添加了long long至少 64 位的新类型,这在所有平台上都有保证。因此,如果您的值在 64 位类型的范围内,请使用unsigned long longoruint64_t/uint_least64_tstrtoull来获取正确的值。

于 2014-06-20T06:16:01.307 回答