从文件中读取字符串并转换为 bitset<12>

read string from file and turn into bitset<12>

本文关键字:bitset gt lt 转换 文件 读取 字符 串并 字符串      更新时间:2023-10-16

嗨,我正在尝试从 txt 文件中读取字符串并将其转换为二进制文件,该文件是 bitset<12>字符串形式。

int main()
{
using namespace std;
std::ifstream f("fruit.txt");
std::ofstream out("result.txt");
std::hash<std::string>hash_fn;
int words_in_file = 0;
std::string str;
while (f >> str){
++words_in_file;
std::bitset<12>* bin_str = new std::bitset<12>[3000];
int temp_hash[sizeof(f)];
std::size_t str_hash = hash_fn(str);
temp_hash[words_in_file] = (unsigned int)str_hash;
bin_str[words_in_file] = std::bitset<12>((unsigned int)temp_hash[words_in_file]);
out << bin_str[words_in_file] << endl;
delete[] bin_str;
}
out.close();
}

但是有错误。如何更改它?

这是我编写的一些代码,可将输入文件"file.txt"转换为二进制文件。它通过获取每个字符的 ascii 值并将该数字表示为二进制值来实现这一点,尽管我不确定如何将bin_str写入此处的文件。

#include <string>
#include <fstream>
#include <streambuf>
#include <bitset>
#include <iostream>
int main(){
std::ifstream f("file.txt");
std::string str((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());  // Load the file into the string
std::bitset<12> bin_str[str.size()]; // Create an array of std::bitset that is the size of the string
for (int i = 0; i < str.size(); i++) {
bin_str[i] = std::bitset<12>((int) str[i]); // load the array
std::cout << bin_str[i] << std::endl; // print for checking
}
}

旁注:

std::bitset<12>可能不是你想要的,如果你看ASCII字符,你可以拥有的最高数字是127,而在二进制中只有7位数字,所以我假设你想要更像std::bitset<7>std::bitset<8>

编辑:如果要将其写入文件,则需要使用std::ios::binary打开一个文件,然后遍历位集数组并将其无符号长代表(从to_ulong()给出)写入为 const char 指针 ((const char*)&ulong_bin)。现在,当您使用二进制编辑器打开文件时,您将看到二进制写入和常规写入之间的区别,但您会注意到像cat这样的程序仍然可以破译您编写为简单 ascii 字母的二进制文件。

std::ofstream out("file.bin", std::ios::binary);
for (int i = 0; i < str.size(); i++) {
unsigned long ulong_bin = bin_str[i].to_ulong();
out.write((const char*)&ulong_bin, sizeof(ulong_bin));
}

编辑:归功于@PeterT

我注意到 VLA(可变长度数组)在 C++11 及更高版本中不受支持,因此应将行std::bitset<12> bin_str[str.size()];更改为以下之一:

std::bitset<12> *bin_str = new std::bitset<12>[str.size()]; // make sure you delete it later
// OR
std::vector<std::bitset<12>> bin_str(str.size());
// OR
std::unique_ptr<std::bitset<12>[]> str_ptr (new std::bitset<12>[str.size()]);