John Doyle
John Doyle

Reputation: 948

how can I memcpy bool vector to char array?

I have two vectors.
One is

std::vector<unsigned char> one_v;

and the other is

std::vector<bool> outputValuesInBits;

I pushed values to both one_v and outputValuesInBits.
Both vectors have two bytes.
one_v[0] and [1] are filled with data which would be 2 bytes.
outputValuesInBits[0] to [15] are filled with data which would be 2 bytes.
Now, I would like to copy(memcpy) data to char array.

I can successfully copy data from one_v vector as following.

 unsigned char* output = new unsigned char[one_v.size()]();
 memcpy(&output, one_v.data(), 2);

But I cannot copy data from outputValuesInBits.
If I do as follow,

unsigned char* output = new unsigned char[outputValuesInBits.size()/8+1]();
memcpy(&output, outputValuesInBits.data(), 2);

It gives me an error

error: invalid use of void expression
     memcpy(&output, outputValuesInBits.data(), 2);

Can anyone please tell me how I can copy the bool vector to char array?

Thank you in advance!

Upvotes: 1

Views: 2519

Answers (3)

Boris
Boris

Reputation: 11

At least in g++ compiler you can use the _M_p member of the vector::iterator, which is the pointer to the data.

Example:

std::vector<bool> vBool(16, false);
vBool[0] = true;
vBool[2] = true;
vBool[13] = true;
std::vector<unsigned char> vChar(2);
unsigned short *ptrUS = reinterpret_cast<unsigned short *>( &(vChar[0]) );
*ptrUS = *reinterpret_cast<unsigned short *>(vBool.begin()._M_p);

std::cout << (unsigned int)vChar[0] << " " << (unsigned int)vChar[1] << "\n";

gives in output '5 32', which corresponds to the numbers with 1st and 3rd bit (5) and with the 6th bit (32).

Upvotes: 1

user5159806
user5159806

Reputation: 92

std::vector<bool> doesn't have a data member function

Upvotes: 3

Serge Ballesta
Serge Ballesta

Reputation: 149185

I'm afraid you cannot in a portable way. Cplusplus page on vector says: The specialization has the same member functions as the unspecialized vector, except data, emplace, and emplace_back, that are not present in this specialization. That means that data in not defined what explains the error when you try to use it.

If portability is not an option, there will be no solution because The storage is not necessarily an array of bool values, but the library implementation may optimize storage so that each value is stored in a single bit. (emphasize mine). My understanding of the may is that you cannot even be sure that the 16 boolean are stored in 2 consecutive bytes: the implementation must only provide you a way to use them (almost) as if they were stored in 16 different booleans.

If you can forget partability, you will have to find the source for you current implementation to know where and how the byte array is stored... but it is not that easy...

Upvotes: 3

Related Questions