+ public static int byteToInt(final byte input) {
+ int result = input;
+ if (result < 0)
+ result = result + 256;
+ return result;
+ }
+
+ public static int decodeValueFromGivenBits(final int encodedBits,
+ final int range, final int bitCount) {
+ final int negativeBit = encodedBits & 1;
+
+ final int remainingBitCount = bitCount - 1;
+
+ if (remainingBitCount == 0) {
+ // no more bits remaining to encode actual value
+
+ if (negativeBit == 0)
+ return range;
+ else
+ return -range;
+
+ } else {
+ // still one or more bits left, encode value as precisely as
+ // possible
+
+ final int encodedValue = (encodedBits >>> 1) + 1;
+
+ final int realvalueForThisBitcount = 1 << remainingBitCount;
+
+ // int valueMultiplier = range / realvalueForThisBitcount;
+ int decodedValue = (range * encodedValue)
+ / realvalueForThisBitcount;
+
+ if (decodedValue > range)
+ decodedValue = range;
+
+ if (negativeBit == 0)
+ return decodedValue;
+ else
+ return -decodedValue;
+
+ }
+ }
+
+ public static int encodeValueIntoGivenBits(int value, final int range,
+ final int bitCount) {
+
+ int negativeBit = 0;
+
+ if (value < 0) {
+ negativeBit = 1;
+ value = -value;
+ }
+
+ final int remainingBitCount = bitCount - 1;
+
+ if (remainingBitCount == 0)
+ return negativeBit;
+ else {
+ // still one or more bits left, encode value as precisely as
+ // possible
+
+ if (value > range)
+ value = range;
+
+ final int realvalueForThisBitcount = 1 << remainingBitCount;
+ // int valueMultiplier = range / realvalueForThisBitcount;
+ int encodedValue = (value * realvalueForThisBitcount) / range;
+
+ if (encodedValue >= realvalueForThisBitcount)
+ encodedValue = realvalueForThisBitcount - 1;
+
+ encodedValue = (encodedValue << 1) + negativeBit;
+
+ return encodedValue;
+ }
+ }
+
+ public static void storeIntegerCompressed8(
+ final BitOutputStream outputStream, final int data)
+ throws IOException {
+
+ if (data < 256) {
+ outputStream.storeBits(0, 1);
+ outputStream.storeBits(data, 8);
+ } else {
+ outputStream.storeBits(1, 1);
+ outputStream.storeBits(data, 32);
+ }
+ }
+