M.K.
M.K.

Reputation: 650

c++ print out bitset of vector<unsigned char>

I am copy the double value to the vector of unsigned char. It will be my buffer for socket, which should contain values of different types. I wanted to test if the coping works correct. I wrote a small code.

vector<unsigned char> buffer(8);
double doubleValue_1 = 8.0;
memcpy(&buffer[0], &doubleValue_1, sizeof( doubleValue_1));

bitset<64>bitset_1(doubleValue_1);
cout << "doubleValue_1: " << bitset_1 << endl;

cout << "buffer: ";
for (int i = 0; i < buffer.size(); i++) {
    bitset<8>bitset_v(buffer.at(i));
    cout << bitset_v;
}

cout << endl << endl;

double doubleValue_2;
memcpy(&doubleValue_2, &buffer[0], sizeof(doubleValue_2));

bitset<64>bitset_2(doubleValue_2);
cout << "doubleValue_2: " << bitset_2 << endl;

And I got the output:

doubleValue_1: 0000000000000000000000000000000000000000000000000000000000001000
buffer:        0000000000000000000000000000000000000000000000000010000001000000
doubleValue_2: 0000000000000000000000000000000000000000000000000000000000001000

How you can see, the first doubleValue_1 represented 8.0. Than I copied this value to vector. And the output is NOT equal to the previous one. But when I coped bytes from vector to double back, I got in doubleValue_2 the same value as in doubleValue_1. My question is, why the output of vector is different than of double? Maybe I print out the vector in wrong way. Could you suggest me how I can do it correctly? Thank you a lot.

Upvotes: 3

Views: 2173

Answers (1)

Nemo
Nemo

Reputation: 71565

bitset<64>bitset_1(doubleValue_1); is casting your double to an unsigned long (because that is what the bitset<64> constructor takes.)

Similarly for bitset<64>bitset_2(doubleValue_2);.

Neither one is actually winding up with the bit representation for a double.

Upvotes: 8

Related Questions