写了个按照bit读取或写入java的IO流的简单代码,保留在博客里备忘。
/**
* 按bit读取的input。
* */
public class BitInput {
private InputStream input;
private int value;
private int next = 7;
public BitInput(InputStream input) {
this.input = input;
}
/**
* 读取一个bit,1,0,-1(文件结束)。
* */
public int readBit() throws Exception {
if (next == 7) {
value = input.read();
if (value == -1) {
return -1;
}
}
int result = (value & (1 << next)) >>> next;
next--;
if (next == -1) {
next = 7;
}
return result;
}
/**
* 读取size个bit。
* */
public int[] readBits(int size) throws Exception {
int[] result = new int[size];
for (int i = 0; i < size; i++) {
int v = readBit();
if (v == -1) {
throw new RuntimeException();
}
result[i] = v;
}
return result;
}
}
/**
* 按bit写出的output。
* */
public class BitOutput {
private OutputStream out;
private int value;
private int next = 7;
public BitOutput(OutputStream out) {
this.out = out;
}
public void writeBitOne() throws Exception {
write(1);
}
public void writeBitZero() throws Exception {
write(0);
}
private void write(int bit) throws Exception {
value = value | (bit << next);
next--;
if (next < 0) {
out.write(value);
value = 0;
next = 7;
}
}
public void writeBits(String bits) throws Exception {
for (int i = 0; i < bits.length(); i++) {
char v = bits.charAt(i);
if (v == '0' || v == '1') {
write(v - '0');
continue;
}
throw new RuntimeException();
}
}
public void writeBits(int[] bits) throws Exception {
for (int bit : bits) {
if (bit == 0 || bit == 1) {
write(bit);
continue;
}
throw new RuntimeException();
}
}
public void close() throws Exception {
if (next == 7) {
return;
}
out.write(value);
}
}