Integer.toBinaryString()失去领先的0

时间:2017-04-20 17:12:07

标签: java byte bit

我目前正在使用Huffman Tree来压缩/解压缩文本文件。目前我的问题是,当写入字节并阅读它们时,我的数字中丢失了任何前导0。

在我的OutputStream类中,我的writeBit()方法,我一次只能输入一位,当我的位数达到8时,我将字节写入文件。目前使用String来构建这个二进制数,尽管在实际写入该位时会出现问题。

HuffmanOutputStream.java:

/**
* Created by Sully on 3/20/2017.
*/

import java.io.IOException;


public class HuffmanOutputStream extends BitOutputStream {

private int count = 0;
private String bytes = "";

public HuffmanOutputStream(String filename, String tree, int totalChars) {
    super(filename);
    try {
        d.writeUTF(tree);
        d.writeInt(totalChars);
    } catch (IOException e) {
    }
}

public void writeBit(int bit) {
    //PRE   bit ==  0   ||  bit ==  1
    if (count < 8) {
        bytes += bit;
        count++;
    }
    try {

        if (count == 8) {
            d.writeByte(Integer.parseInt(bytes, 2));
            count = 0;
            bytes = "";
        }

    } catch (IOException e) {
        e.printStackTrace();
    } 
}


public void close() {

}
}

出现问题的一个例子,对于我的文本文件,我构造的第一个字节是01100001,虽然当我使用Integer.parseInt(byte,2)时,给定的整数是97,当它被读取时作为二进制数,只返回1100001.由于霍夫曼树依赖于这些0被包括在内,我怎么能保持这个0?还要确保在0到位的情况下正确读取?

HuffmanInputStream.java:

/**
* Created by Sully on 3/20/2017.
*/

import java.io.IOException;

public class HuffmanInputStream extends BitInputStream {
  private String tree;
  private int totalChars;

  private int currentByte;
  private int bitCount;
  private static final int BYTE_SIZE = 8;
  private int[] bufferedBits = new int[BYTE_SIZE];


public HuffmanInputStream(String filename) {
    super(filename);

    try {
        tree = d.readUTF();
        totalChars = d.readInt();
        currentByte = 0;
        bitCount = 8;

    } catch (IOException e) {
    }
}


public int readBit() {

    if (currentByte == -1) {
        return -1;
    }


    if (bitCount == 8) {
        try {
            currentByte = d.read();
            if(currentByte == -1){
                return -1;
            }
            String binary = Integer.toBinaryString(currentByte);
            for (int x = 0; x < binary.length(); x++) {
                bufferedBits[x] = Character.valueOf(binary.charAt(x));
            }
            bitCount = 0;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    int val = bufferedBits[bitCount];

    bitCount++;

    return val % 2;


}

public String getTree() {
    return tree;
}

public int totalChars() {
    return totalChars;
}

public void close() {
    try {
        d.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

我知道这个问题有点冗长,但我们非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

我认为您希望有足够的前导0来表示从String 8返回的Integer#toBinaryString的长度;以下代码将为您实现此目的:

String binary = String.format("%8s", Integer.toBinaryString(currentByte)).replace(' ', '0');