質問

Can anyone explain why the following does not work for me please?

#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;
}

Only the lowest 32 bits of the bitset are set correctly. The highest bits remain 0. I have tried also using unsigned long long in place of uint64_t.

I am using windows vista and the code::blocks editor which was only recently installed.

I have tried installing code::blocks onto another machine I have running windows xp and the problem is the same.

edit 2 --

I changed the code to the following

#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;
}

and now when I input ffffffffff i get the output

ok
1099511627775
addr = 0000000000000000000000000000000011111111111111111111111111111111

Thanks.

役に立ちましたか?

解決

You are using a C++03 compiler. In C++03, the bitset constructor takes an unsigned long parameter, which on your platform is 32 bits, so you lose the upper bits.

In C++11, this was changed to take an unsigned long long, so your code would have worked. It would also work on a platform where long is 64 bits.

You will need to use a different method to convert a 64-bit integer to a binary representation string or to a std::bitset, for example a loop going over all bits.

You can also construct the bitset in two parts:

set::bitset<64> bs = (std::bitset<64>(val >> 32) << 32)  | 
                     std::bitset<64>(val & 0xffffffff);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top