【发布时间】:2021-03-17 20:46:21
【问题描述】:
所以我将位字符串转换为 int 类型的向量,然后将向量的元素推入 dynamic_bitset 对象并将该对象写入文件。这是我的代码。
#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;
}
};
这里是将位串转换为整数向量类型的代码。
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;
}
我尝试打印“Bits”的元素,但它不打印任何内容,并且长度也为 1。 我做错了什么?
【问题讨论】:
-
你在字符串 s 中存储了什么?
-
我给出了一个类似“10110100”的字符串。并将它们放入整数向量中,如 1、0、1、1、0、1、0、0。
-
您希望向量 nums 是这样的:{1, 0, 1, 1, 0, 1, 0, 0}?你为什么使用字符串流,而不是通过字符串迭代?
-
如果我遍历字符串,它会给我像 {49, 48, 49, 49, 48, 49, 48, 48} 这样的 ascii 值。
-
是的,那是因为字符存储在 ASCII 码中。看我的回答。
标签: c++ string c++11 vector boost-dynamic-bitset