Updated Java BitBuffer code to add methods and make the class public.

This commit is contained in:
Project Nayuki 2017-08-17 20:12:42 +00:00
parent 493d3c31f2
commit 7a2555816b
1 changed files with 21 additions and 1 deletions

View File

@ -30,7 +30,7 @@ import java.util.Objects;
/**
* An appendable sequence of bits. Bits are packed in big endian within a byte.
*/
final class BitBuffer {
public final class BitBuffer implements Cloneable {
/*---- Fields ----*/
@ -57,6 +57,14 @@ final class BitBuffer {
}
// Returns the bit at the given index, yielding 0 or 1, or throwing IndexOutOfBoundsException.
public int getBit(int index) {
if (index < 0 || index > bitLength)
throw new IndexOutOfBoundsException();
return data.get(index) ? 1 : 0;
}
// Returns a copy of all bytes, padding up to the nearest byte. Bits are packed in big endian within a byte.
public byte[] getBytes() {
byte[] result = new byte[(bitLength + 7) / 8];
@ -85,4 +93,16 @@ final class BitBuffer {
}
}
// Returns a copy of this bit buffer object.
public BitBuffer clone() {
try {
BitBuffer result = (BitBuffer)super.clone();
result.data = (BitSet)result.data.clone();
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
}