Answer the question
In order to leave comments, you need to log in
How to organize bitwise recording?
I'm trying to implement a Huffman algorithm that will compress a text file. A tree has already been built, which has:
tree->simvol // char in which the character itself is stored (for example 'a')
tree->code // string, the binary code for this character (for example 1001)
I need to write a function that it will go through the source file, and will read each character, comparing it with the characters in my tree, and finding the right one, it will write a sequence of ones and zeros (tree->code) to the new file.
The difficulty is in the bitwise notation, because I have no idea how to organize it. Let me explain - I need, for example, the sequence 10011110 to take exactly 8 bits, i.e. one or zero would take 1 bit, otherwise compression will not work (if I just write "1001" instead of the letter "a" as a set of characters, and not bits).
void shifr(){
ifstream myfile("file.txt");//открыли файл
char ch;
if (!myfile.is_open()) // если файл не открыт
cout << "Файл не может быть открыт!\n"; // сообщить об этом
else
{
while (myfile.get(ch))//проходимся посимвольно по всему текстовому файлу
{
find_char(ch);//находим нужный символ в дереве и записываем код этого символа в новый файл
}
myfile.close();
}
}
void find_char(spisok *&tree, char ch) {//рекурсивный обход дерева и поиск в нем символа
if (tree->left==NULL && tree->right==NULL && tree->simvol==ch) {
//???
//вот тут нужно как-то записать код из tree->code в новый файл...
//???
}
if (tree->left!=NULL) {
find_char(tree->left,ch);
}
if (tree->right!=NULL) {
find_char(tree->right,ch);
}
}
Answer the question
In order to leave comments, you need to log in
You can create a variable of type char and toggle individual bits in it using a bitwise or
char result = 0;
// допустим, что код - 8 бит
for (char* x = tree->code, int y = 0; *x != '\0'; x++, y++)
if (*x == '1')
*x |= 1 << (8 - y);
1) Write bytes to vector<bool>
(the solution is trivial)
2) Write vector<bool>
to a file (the solution is on the Internet)
And never use
alenacpp.blogspot.ru/2005/06/vector.html
Tip #18 (Meyers)!
You can, for example, store everything in the inte or, in extreme cases,std::bitset.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question