2

I have a vector< bool> of binary data that I need to write into a binary file bit by bit (I know it has to be in multiples of 8 for the bytes, just assume it is). I then need to re - read that data back into a vector< bool>. I am having immense difficulty getting this to work.

The data must start and finish in the vector< bool>. Please if anyone can advise on simple syntax to achieve this, that would be a massive help.

genpfault
  • 51,148
  • 11
  • 85
  • 139
Drew C
  • 91
  • 1
  • 6
  • 1
    But you already asked this yesterday at http://stackoverflow.com/questions/4861898/outputting-bit-data-to-binary-file-c. – TonyK Feb 02 '11 at 14:38
  • Yeah, I basically want to copy the whole vector< bool> data into a file and then recollect it (it contains a huffman encoded data). I managed to get this to work yesterday with small code following something along the lines as given in here http://courses.cs.vt.edu/~cs2604/fall02/binio.html for the "Reading and Writing Complex Data" but doesn't work in main program, giving me errors. You can see my other post for this. – Drew C Feb 02 '11 at 14:50
  • @Drew C : look at my answer and tell me what the proble is exactly ... – neuro Feb 02 '11 at 14:56
  • @Drew C: By the way, is that homework ? – neuro Feb 02 '11 at 14:56
  • Kind of, it's part of an exercise. I normally program in fortran to calculate things, so new to c++ and memory management things. Is there a limit to how large the bitsets can go? And can you define the bitset size in the middle of the program? – Drew C Feb 02 '11 at 15:04
  • Don't know if you see this Neuro, but thanks so much for that, managed to get it to work!!! Relief! – Drew C Feb 02 '11 at 16:09
  • @drew C: I'm glad you succeed :) As you should have see, bitsets has fixed size when declared, so they can not grow after creation. I think there is a limit to the size (besides the limit of your system of course). If the answer is OK with you, you can upvote and accept it, it will help others eventually .. Good luck with your C++ code. – neuro Feb 03 '11 at 15:16

1 Answers1

1

The simplest way is to use std::bitset. It has a constructor and a to_ulong member you can use to do your conversions. Then you just have to convert a vector of size eight to bitset and vice versa. Beware of the order the bits are stored in your vector and the endianess if it applies in your file ...

I'm in a good day, here is some "pseudo" code :

// you will guess declarations
// you might have to reverse bit order dependaing of how you store bits

for(int i = 0; i < 8; ++i)
{
    if(myvector[i]) mybistset.set(i);
}

char toWriteInFile = bitset.to_ulong();

// write in file

[...]

char readFromFile;

// read from file

std::bitset mybitset(readFromFile);

// same remarks

for(int i = 0; i < 8; ++i)
{
    myvector[i] = mybistset[i];
}

Of course, you have to manage the vector size is greater than 8 part ;)

my2c

neuro
  • 14,948
  • 3
  • 36
  • 59