簡體   English   中英

十六進制輸入到bitset <64> C ++

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM