簡體   English   中英

霍夫曼編碼-處理unicode

[英]Huffman Coding - Dealing with unicode

我已經在Java中實現了霍夫曼編碼,可對輸入文件中的字節數據進行處理。 但是,它僅在壓縮ascii時有效。 我想擴展它,以便它可以處理大於1個字節長的字符,但是我不確定如何確切地做到這一點。

private static final int CHARS = 256;     
private int [] getByteFrequency(File f) throws FileNotFoundException {
    try {
        FileInputStream fis = new FileInputStream(f);
        byte [] bb = new byte[(int) f.length()];
        int [] aa = new int[CHARS];
            if(fis.read(bb) == bb.length) {
                System.out.print("Uncompressed data: ");
                for(int i = 0; i < bb.length; i++) {
                        System.out.print((char) bb[i]);
                        aa[bb[i]]++;
                }
                System.out.println();
            }
        return aa;
    } catch (FileNotFoundException e) { throw new FileNotFoundException(); 
    } catch (IOException e) { e.printStackTrace(); }
    return null;
}

例如,這就是我用來獲取文件中字符頻率的方式,顯然,它僅適用於單個字節。 如果給它一個unicode文件,則會在aa[bb[i]]++;得到ArrayIndexOutOfBoundsException aa[bb[i]]++; ,且i通常是一個負數。 我知道這是因為aa[bb[i]]++; 僅查看一個字節,而unicode字符將不止一個,但是我不確定如何更改它。

有人可以給我一些指示嗎?

請嘗試以下操作:

private static final int CHARS = 256;     
private int [] getByteFrequency(File f) throws FileNotFoundException {
    try {
        FileInputStream fis = new FileInputStream(f);
        byte [] bb = new byte[(int) f.length()];
        int [] aa = new int[CHARS];
            if(fis.read(bb) == bb.length) {
                System.out.print("Uncompressed data: ");
                for(int i = 0; i < bb.length; i++) {
                        System.out.print((char) bb[i]);
                        aa[((int)bb[i])&0xff]++;
                }
                System.out.println();
            }
        return aa;
    } catch (FileNotFoundException e) { throw new FileNotFoundException(); 
    } catch (IOException e) { e.printStackTrace(); }
    return null;
}

如果我是正確的(我尚未測試過),則您的問題是該字節是Java中的一個SIGNED值。 強制轉換為整數+將其掩碼為0xff應該正確處理。

暫無
暫無

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

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