So I am converting the bit string to a vector of type int and then pushing the elements of vector in dynamic_bitset object and writing that object into file. Here is my code.
#include <iostream>
#include <boost/dynamic_bitset.hpp>
#include <fstream>
#include <streambuf>
#include "Utility.h"
using namespace std;
using namespace boost;
class BitOperations {
private:
string data;
int size;
dynamic_bitset<unsigned char> Bits;
string fName;
public:
// BitOperations(dynamic_bitset<unsigned char> b){
// Bits = b;
// size = b.size();
// }
// BitOperations(dynamic_bitset<unsigned char> b, string fName){
// Bits = b;
// this->fName = fName;
// size = b.size();
// }
BitOperations(string data, string fName){
this->data = data;
this->fName = fName;
}
void writeToFile(){
if (data != ""){
vector<int> bitTemp;
bitTemp = extractIntegers(data);
for (int i = 0; i < bitTemp.size(); i++){
Bits.push_back(bitTemp[i]);
}
// for (int i = 0; i < bitTemp.size(); i++){
// cout << Bits[i] << " ";
// }
// cout << endl;
}
ofstream output(fName, ios::binary);
ostream_iterator<char> osit(output);
to_block_range(Bits, osit);
}
dynamic_bitset<unsigned char> readFromFile(){
int count = 0;
ifstream t(fName);
string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
cout << str << endl;
dynamic_bitset<unsigned char> b;
int bitLen = str.length() * 8;
for (int i = 0; i < str.length(); i++){
for (int j = 0; j < 8; ++j){
bool isSet = str[i] & (1 << j);
b.push_back(isSet);
}
}
return b;
}
};
Here is the code for converting bit string into vector type of integer.
vector<int> extractIntegers(string s){
stringstream stream;
stream << s;
string tmp;
int flag;
vector<int> nums;
while (!stream.eof()){
stream >> tmp;
if (stringstream(tmp) >> flag){
nums.push_back(flag);
}
tmp = "";
}
return nums;
}
I tried to print the elements of "Bits" but it does not print anything and also has length of 1. What am I doing wrong?
Aucun commentaire:
Enregistrer un commentaire