我正在创建一个文件压缩和解压,我不知道解压时如何处理剩余的位。
例如,我有 63 位,由于字节 = 8 位,63 % 8 = 7 仍然有 7 位。现在,每当我解压缩文件时,它都会缺少字符。
这是我的代码:
Node* root = head->node; // Save the root of the Huffman tree
Node* current = root; // Initialize the current node
char byte; // Read bytes for decompression
while (compressedFileStream.get(byte)) {
for (int i = 7; i >= 0; i--) {
if (compressedFileStream.eof()) {
break; // Break out of the loop if end of file is reached
}
// Traverse the tree based on each bit in the byte
char bit = (byte & (1 << i)) ? '1' : '0';
if (bit == '0') {
current = current->left;
}
else if (bit == '1') {
current = current->right;
}
if (current->left == NULL && current->right == NULL) {
decompressedFile << current->character;
current = root; // Reset current to the root for the next character
}
}
}
我应该怎样做才能解压我的压缩文件而不丢失字符。
您的代码当前执行以下操作:
我发现了一些问题:
if (compressedFileStream.eof())
放入 for
循环中看起来就像您希望文件在字节中间结束。这种情况不会发生。for
循环之后推动测试:
Node* root = head->node; // Save the root of the Huffman tree
Node* current = root; // Initialize the current node
char byte; // Read bytes for decompression
while (compressedFileStream.get(byte)) {
for (int i = 7; i >= 0; i--) {
// Traverse the tree based on each bit in the byte
char bit = (byte & (1 << i)) ? '1' : '0';
if (bit == '0') {
current = current->left;
}
else if (bit == '1') {
current = current->right;
}
if (current->left == NULL && current->right == NULL) {
decompressedFile << current->character;
current = root; // Reset current to the root for the next character
}
}
if (compressedFileStream.eof()) {
break; // Break out of the loop if end of file is reached
}
}
// Close the file / free resources here.