按照bit读取或写入java的IO流

本文提供了一个简单的Java实现,用于按位读取和写入输入输出流。包括BitInput类用于读取位,BitOutput类用于写出位。适用于需要精细控制二进制数据处理的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写了个按照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);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值