jinahya / bit-io

A library for reading/writing arbitrary length of bits.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Optimization for Quotient and Remainder

opened this issue · comments

Re:

https://github.com/jinahya/bit-io/blob/develop/src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java#L116

There are a few places in the code base that use integer division and modular arithmetic. It may be possible to replace them with faster bit-shifting equivalents. Imagine a variable mPosition that points to a particular bit within a byte array. Retrieving the value of the bit can be accomplished as follows, where BYTE_INDEX_SHIFT equals 3 (i.e., log base 2 of 8):

final int byteIndex = (int) (mPosition >> BYTE_INDEX_SHIFT);
final int bitIndex = (int) (mPosition - (byteIndex << BYTE_INDEX_SHIFT));

final int bitShifts = Byte.SIZE - bitIndex - 1;
final int bit = (mSequence[byteIndex] & (1 << bitShifts)) >> bitShifts;

I suspect such calculations will be more efficient than using %, especially on older hardware.