逐位读取文件以形成霍夫曼编码树

时间:2012-11-29 15:40:31

标签: bit-manipulation huffman-code

这个问题要求我从文件中读取一个标题,即基于位的压缩文件,以提取构建树所需的必要信息。通常头部看起来像这样:" 1g1o01s1 01e1h01p1r0000013 \ n" 1表示叶节点,0表示我们何时需要形成树。还有一个额外的0,它将标题信息与文件中的字符数分开。我有一切可以创建树并打印它的内容,但是我在阅读信息时遇到了麻烦。当我执行代码时,我的一个输出包含一个' 1'它不应该在叶子里。这是否意味着当我想要获取位时,我会错过处理字节?

Command line output

  

以下是main的代码:

while((num = ReadBit(fp, 'b')))
{
    //printf("num = %c\n", num);
    if(num == '1')
    {
        letter = ReadBit(fp, 'c');
        printf("letter = %c\n\n", letter);
        new_node = CreateNode(letter);
        Push(&Fake, new_node);
        Onecount++;
    }
    if(num == '0')
    {
        First = Pop(&Fake);
        Second = Pop(&Fake);
        new_node = malloc(sizeof(LEAF));
        new_node-> rchild = First;
        new_node-> lchild = Second;
        Push(&Fake, new_node);
        Zerocount++;
    }

    if(Onecount == Zerocount)
    {
        break;
    }

}
  

以下是ReadBit功能的代码

int ReadBit(FILE *fp, char mode)
{  
unsigned char value;
unsigned static int count = 0;
unsigned static char letter = 0;
unsigned static char byte;
unsigned static int place;

    /* This is the bit mode, it will grab the first bit from the current byte and return it */
if(mode == 'b')
{
    if(count == 0)
    {
        fread(&byte, 1, 1, fp);
    }

    value = (((byte & (1 << (7 - count))) == 0) ? '0' : '1');
    count++;
    letter = byte << count;

    if(count == 8)
    {
        count =  0;
    }

    place = 8 - count;
}

/*This is "character" mode. It will grab enough bits in order to create a byte that will be a letter */
if(mode == 'c')
{
    if(count == 0)
    {
        fread(&letter, 1, 1, fp);
    }
    else
    {
        /* This will read in a new byte and add in as many bits as we need to complete a byte from the previously saved bits */
        fread(&byte, 1, 1, fp);
        value = letter + (byte >> place);
    }
}

return(value);
 }

0 个答案:

没有答案