[英]hex input to bitset<64> C++
谁能解释为什么以下这些对我不起作用?
#include <iostream>
#include <string>
#include <sstream>
#include <bitset>
using namespace std;
int main()
{
string tempString;
uint64_t tempValue;
cout << "enter addr in hex : ";
cin >> tempString;
istringstream ost(tempString);
ost >> hex >> tempValue;
bitset<64> addr(tempValue);
cout << "addr = " << addr << endl;
}
仅正确设置了位集中的最低32位。 最高位保持为0。我也尝试使用unsigned long long代替uint64_t。
我正在使用Windows Vista和最近才安装的code :: blocks编辑器。
我尝试将代码::: blocks安装到另一台运行Windows XP的计算机上,问题是相同的。
编辑2-
我将代码更改为以下内容
#include <iostream>
#include <string>
#include <sstream>
#include <bitset>
using namespace std;
int main()
{
string tempString;
uint64_t tempValue;
cout << "enter addr in hex : ";
cin >> tempString;
istringstream ost(tempString);
if (ost >> hex >> tempValue) cout << "ok" << endl; else cout << "bad" << endl;
ost >> hex >> tempValue;
cout << tempValue << endl;
bitset<64> addr(tempValue);
cout << "addr = " << addr << endl;
}
现在当我输入ffffffffff
我得到了输出
ok
1099511627775
addr = 0000000000000000000000000000000011111111111111111111111111111111
谢谢。
您正在使用C ++ 03编译器。 在C ++ 03,该bitset
的构造函数需要一个unsigned long
的参数,它使用的平台是32位,所以你失去的高位。
在C ++ 11中,将其更改为unsigned long long
,所以您的代码可以正常工作。 它也可以在long
为64位的平台上工作。
您将需要使用其他方法将64位整数转换为二进制表示形式的字符串或std::bitset
,例如,遍历所有位的循环。
您还可以分两部分构造位集:
set::bitset<64> bs = (std::bitset<64>(val >> 32) << 32) |
std::bitset<64>(val & 0xffffffff);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.