Skip to content

Instantly share code, notes, and snippets.

@kzkn
Last active November 11, 2019 23:35
Show Gist options
  • Save kzkn/b8ff1b52edd9a90fa1a5 to your computer and use it in GitHub Desktop.
Save kzkn/b8ff1b52edd9a90fa1a5 to your computer and use it in GitHub Desktop.
import java.nio.ByteBuffer;
public class BitStream {
private final byte[] bytes;
private final int numOfBits;
private int pos;
public BitStream(ByteBuffer buf) {
bytes = new byte[buf.remaining()];
int p = buf.position();
buf.get(bytes);
buf.position(p);
this.numOfBits = bytes.length * 8;
this.pos = 0;
}
public int getBit() {
if (pos >= numOfBits)
throw new IllegalStateException();
int i = pos / 8;
int a = pos % 8 + 1;
++pos;
return (bytes[i] >> (8 - a)) & 0x1;
}
public int getBits(int bits) {
if (bits > 32)
throw new IllegalArgumentException();
if (bits + pos > numOfBits)
throw new IllegalArgumentException();
if (bits == 0)
return 0;
int r = 0;
for (int i = 0; i < bits; ++i) {
r |= (getBit() << (bits - i - 1));
}
return r;
}
public int peekBits(int bits) {
int p = pos;
int r = getBits(bits);
pos = p;
return r;
}
public int getRemaining() {
return numOfBits - pos;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment