簡體   English   中英

實施霍夫曼樹

[英]Implementing Huffman Tree

我有一個程序可以根據在文本輸入文件中讀取的 ascii 字符頻率生成霍夫曼樹。 霍夫曼代碼存儲在一個包含 256 個元素的字符串數組中,如果未讀取字符則為空字符串。

我現在試圖通過編寫一個函數來實現霍夫曼樹,該函數采用存儲在字符串數組中的霍夫曼代碼並將輸入文件的編碼輸出到輸出文件中。

我很快意識到我目前的方法違背了任務的意義。 我曾嘗試簡單地將代碼字符串復制到輸出文件,使我的編碼輸出文件比輸入文件大。

我希望在更改我當前的函數方面得到幫助,以便它可以將位輸出到輸出文件中,使輸出文件小於輸入文件。 我被卡住了,因為我目前只讀取和寫入字節?

我當前的功能(fileName 是輸入文件參數,fileName2 是輸出文件參數):

void encodeOutput(const string & fileName, const string & fileName2, string code[256]) {
    ifstream ifile;//to read file
    ifile.open(fileName, ios::binary);
    if (!ifile)//to check if file is open or not
    {
        die("Can't read again"); // function that exits program if can't open
    }
    ofstream ofile; 
    ofile.open(fileName2, ios::binary); 
    if (!ofile) {
        die("Can't open encoding output file"); 
    }
    int read;
    read = ifile.get();//read one char from file and store it in int
    while (read != -1) {//run this loop until reached to end of file(-1)
        ofile << code[read]; //put huffman code of character into output file
        read = ifile.get();//read next character
    }
    ifile.close();
    ofile.close();
}

你不能只使用ofile << code[read]; 如果你需要的是寫,最小單位ofstream理解是一個字節。

為了克服這一點,你可以在你的位寫某種“位緩沖區”(的char會做),並出來,一旦有8位。 我不知道你的代碼字符串是什么樣的,但這應該是:

char buffer = 0, bit_count = 0;
while (read != -1) {
  for (int b = 0; b < code[read].size(); b++) {
    buffer << 1;
    buffer |= code[read][b] != 0;
    bit_count++;
    if (bit_count == 8) {
      ofile << buffer;
      buffer = 0;
      bit_count = 0;
    }
  }
  read = ifile.get();
}

if (bit_count != 0)
  ofile << (buffer << (8 - bit_count));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM