Hi I'm trying to read string from txt file and transform it into binary file which is bitset<12> string form.
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();
}
but there is error. How can I change it?
Here is some code that I wrote that turns the input file
"file.txt"
into binary. It does this by taking the ascii value of each character and representing that number as a binary value, although I'm not sure how to writebin_str
to a file here.SIDE NOTE:
EDIT:std::bitset<12>
may not be what you want, if you look at ascii characters the highest number you can have is 127 and in binary that's only 7 digits so I'd assume you'd want something more likestd::bitset<7>
orstd::bitset<8>
If you want to write it to a file you'll need to open a file with
std::ios::binary
and then loop through the array of bitsets and write their unsigned long representative, given fromto_ulong()
, as a const char pointer ((const char*)&ulong_bin
). Now when you open the file with a binary editor you will see the difference between the binary write and the regular write, but you'll notice that programs likecat
can still decipher the binary you've written as simple ascii letters.EDIT: Credit to @PeterT
It has come to my attention that VLAs, variable length arrays, are not supported in C++11 and up so the line
std::bitset<12> bin_str[str.size()];
should be changed to one of the following: