Class BitInputStream
This class provides bit-level reading capabilities, allowing you to read any number of bits from an underlying input stream. Bits are read from most significant to least significant within each byte.
Example usage:
InputStream input = new ByteArrayInputStream(new byte[]{0b10101010, 0b11001100});
BitInputStream bis = new BitInputStream(input);
int first3Bits = bis.readBits(3); // Returns 0b101 (5)
int next5Bits = bis.readBits(5); // Returns 0b01010 (10)
int next8Bits = bis.readBits(8); // Returns 0b11001100 (204)
This class is useful for applications that work with bit-packed data formats, such as custom compression algorithms, network protocols, or binary file formats where data is not byte-aligned.
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionBitInputStream(InputStream inputStream) Creates a new BitInputStream that reads bits from the specified input stream. -
Method Summary
Modifier and TypeMethodDescriptionintreadBits(int bitCount) Reads the specified number of bits from the input stream.
-
Constructor Details
-
BitInputStream
Creates a new BitInputStream that reads bits from the specified input stream.- Parameters:
inputStream- the underlying input stream to read bytes from. Must not be null.
-
-
Method Details
-
readBits
Reads the specified number of bits from the input stream.Bits are read from most significant to least significant. The returned value is assembled with the first bit read becoming the most significant bit of the result.
If the end of the stream is reached while reading, the remaining bits will be zero-filled. Reading zero bits returns zero.
When crossing byte boundaries, the method automatically reads the next byte from the underlying stream.
- Parameters:
bitCount- the number of bits to read (0 to 32). Values greater than 32 may produce unexpected results.- Returns:
- the assembled bits as an integer value, with the first bit read becoming the most significant bit of the result.
- Throws:
IOException- if an I/O error occurs while reading from the underlying stream.
-