Hi... I am trying to write Huffman codes, which are a string of bits contained in a vector<bool>, to a file. I wrote a simple test program to see how I would do this,
std::uint8_t F = 10111001;
std::ofstream K("C:/Users/WDR/Desktop/kml.enc", std::ios::binary);
for(int i = 0; i < 256; i++)
{
K << F;
}
It didn't work and I was pointed out that the variable F is a decimal number and that I had to write it as std::uint8_t F = 0xB9 in order to write the exact byte. I was also told that I don't need this representation when writing from file to file directly because this is just a C++ representation and files are written with the exact bytes since they already in binary. However, since I am writing Huffman codes generated by the C++ program, they would be strings of 1's and 0's. I need to write these as individual bits to the compressed file. I was able to pack these 8 bits at a time to a std::uint8_t and write the packed byte to the file. The file is being written correctly with the individual numbers as bits. However, after packing the bits, the resulting byte is going to be a decimal number and hence, the byte in the file changes when I write it. Is there a way of changing this to a '0x' prefixed hex value so that it can be written correctly to the file? Here's what I'm doing (it's just a test),
std::vector<bool> L;
L.push_back(1);
L.push_back(0);
L.push_back(1);
L.push_back(1);
L.push_back(0);
L.push_back(1);
L.push_back(0);
L.push_back(1);
std::uint8_t J = 0;
for(int i = 0; i < 8; i ++)
{
if(L[i] == 1)
{
J |= 1;
}
J <<= 1;
}
// J becomes decimal 10110101 instead of 0xB5
std::ofstream K("C:/Users/WDR/Desktop/nz.enc", std::ios::binary);
for(int i = 0; i < 256; ++i)
{
K << J;
}
Also, how would I read this written file again bit by bit for decompression? This entire question could be a simple and silly one, but I couldn't find a proper answer on searching. I would really appreciate it if someone took the time to clarify and answer this for me. Thank you very much.