Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one store a vector<bool> or a bitset into a file, but bit-wise?

How to write bitset data to a file?

The first answer doesn't answer the question correctly, since it takes 8 times more space than it should.

How would you do it ? I really need it to save a lot of true/false values.

like image 335
jokoon Avatar asked Jan 12 '11 08:01

jokoon


People also ask

Is Bitset faster than vector bool?

As bitset stores the same information in compressed manner the operation on bitset are faster than that of array and vector.

What is a vector Boolean?

The vector<bool> class is a partial specialization of vector for elements of type bool . It has an allocator for the underlying type that's used by the specialization, which provides space optimization by storing one bool value per bit.

How is Bitset implemented?

Let's implement bitset in C++, such that following operations can be performed in stated time complexities : init(int size): initializes a bitset of size number of 0 bits. void fix(int pos): Change the bit at position pos to 1.


1 Answers

Simplest approach : take consecutive 8 boolean values, represent them as a single byte, write that byte to your file. That would save lot of space.

In the beginning of file, you can write the number of boolean values you want to write to the file; that number will help while reading the bytes from file, and converting them back into boolean values!

like image 144
Nawaz Avatar answered Sep 24 '22 02:09

Nawaz