0
votes

I have a very large (>1 million elements) std::vector that I need to send between two processes using TCP sockets. The reason I'm using std::vector is because I would rather send true and false across as single bits instead of taking up a whole byte (since the data size is so large).

I'm doing some small test cases so that I'm not limited by the maximum transfer size of TCP until I know that everything is working. Essentially, what I'm doing is

int vec[bits->size()]; 
copy(bits->begin(), bits->end(), vec);

so that it can be sent across the socket. Clearly, something isn't working. If vec contains 1 0 1 0 1 0 1, I receive 1000 0000 1000 0000 1000 0000 1000.

It's obviously expanding the bit vector in the copy. My question is this: how do I reinterpret the bit vector as something that can be sent over the socket, while keeping the size limitations of the original vector?

1
You can't for a generic implementation. Sorry. - user541686
However if you have a particular implementation in mind then it is probably possible. - user541686
int vec[bits->size()]; Is this variable-sized array? What is type of bits? - Neil Kirk
Variable size arrays are not standard C++. You should be explicit about the types of variables when you ask questions, I can assume, but I won't be able to know if my assumptions are right: please explicitly write the type of bits in your question. Please ensure that the code snippet you post actually compiles. - Yakk - Adam Nevraumont
Thanks for your help. Part of my problem was earlier in the code in unrelated sections. What I plan to do is make it work with expansion and see if it's too slow, and then revisit other ways to optimize. - alephtwo

1 Answers

2
votes

Even though vector<bool> stores the data as bits, this is transparent to accesses through iterators. Therefore it is working as intended that copying a vector of bools into an array of ints, converts each single bool value into an integer as 0 or 1. You may be able to get away with unsigned char *bit_ptr = reinterpret_cast<unsigned char *>(&bits[0]) but it's not guaranteed. You will either need to process the vector and produce the bits yourself or use a new data structure. You could consider some kind of dynamic bitset (I believe there's one in Boost) or possibly vector<bitset<N>> which will be fairly easy to convert into a bit array using a for loop and bitset's to_ulong function.