reading/writing bits in java


I’ve written a small yet handy library for reading/writing arbitrary length of bits in java.

Apache Subversion

svn co http://jinahya.googlecode.com/svn/trunk/com.googlecode.jinahya/bit-io/

Apache Maven

<dependency>
  <!-- resides in maven central repo -->
  <groupId>com.googlecode.jinahya</groupId>
  <artifactId>bit-io</artifactId>
  <version>1.0-alpha-15</version>
</dependency>

Reading from an InputStream

final InputStream stream; // given

final BitInput input = new BitInput(new BitInput.StreamInput(stream));

final boolean b = input.readBoolean(); // reads a 1-bit boolean
final int i = input.readUnsignedInt(27); // reads a 27-bit unsigned int
final long l = input.readLong(48); // reads a 48-bit signed long

input.align(1); // align to 8-bit byte; padding

Reading from a ByteBuffer

final ByteBuffer buffer; // given

final BitInput input = new BitInput(new BitInput.BufferInput(buffer));

// goes same

Writing to an OutputStream

final OutputStream stream; // given

final BitOutput output = new BitOutput(new BitOutput.StreamOutput(stream));

output.writeBoolean(true); // writes a 1-bit boolean
output.writeInt(17, 0x00); // writes a 17-bit signed int
output.writeUnsignedLong(54, 0x00L); // writes a 54-bit unsigned long

output.align(4); // align to 32-bit byte; discarding

Writing to a ByteBuffer

final ByteBuffer buffer; // given

final BitOutput output = new BitOutput(new BitOutput.BufferOutput(buffer));

// goes same
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s