我试图将 45 位二进制数转换为十六进制数,但在编译时出现溢出错误,但在在线 C++ 编译器上应用代码时,它可以工作。我的平台是X64。请提供任何帮助。
int main()
{
stringstream ss;
string binary_str("111000000100010010100000110101001000100011000");
bitset<45> n(binary_str);
string f;
ss << hex << n.to_ulong() << endl; // error happens here
f = ss.str();
cout << f;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当在在线 C++ 编译器上编译上面的代码时,我得到了正确的结果,即 OX1c08941a9118。
unsigned long是 32 位,带 MSVC。编译 x64 时也是如此。您需要unsigned long long获取一个 64 位整数,因此在这种情况下您可以使用to_ullong:
ss << hex << n.to_ullong() << endl;
Run Code Online (Sandbox Code Playgroud)