mercredi 6 juillet 2016

How to save a bool vector to a stringstream?

I need to save an array of bits into a file, but I need it to be variable in size.

I tried the code below and it returns a different value every execution (never the correct value). Does anybody know why and how I could do it properly?

int a = 42; 
vector<bool> v;
int total_bits = 32; // only example, it will be a variable size

// convert int to 0's and 1's
while(v.size()!=total_bits){
    v.push_back(a & 1);
    if(a!=0)
        a >>=1;
}
reverse(v.begin(), v.end());

// save to file
ofstream output;
stringstream output_ss;
output.open("test.txt", ios::binary | ios::out);
output_ss.write((char*)&v, total_bits/8);
output<<output_ss.rdbuf();

// read from file
ifstream input;
input.open("test.txt", ios::binary | ios::in);
int b;
input>>b;
cout<<"b = "<<b<<endl; // returning incorrect value
input.close();

Aucun commentaire:

Enregistrer un commentaire