NBitInteger { public static int decode(ByteBuffer buffer, int n) { if (n == 8) { int nbits = 0xFF; int i = buffer.get() & 0xff; if (i == nbits) { int m = 1; int b; do { b = 0xff & buffer.get(); i = i + (b & 127) * m; m = m * 128; } while ((b & 128) == 128); } return i; } int nbits = 0xFF >>> (8 - n); int i = buffer.get(buffer.position() - 1) & nbits; if (i == nbits) { int m = 1; int b; do { b = 0xff & buffer.get(); i = i + (b & 127) * m; m = m * 128; } while ((b & 128) == 128); } return i; }  static int octectsNeeded(int n, int i); static void encode(ByteBuffer buf, int n, int i); static int decode(ByteBuffer buffer, int n);  }
@Test void testDecode() { testDecode(6, 0, "00"); testDecode(6, 1, "01"); testDecode(6, 62, "3e"); testDecode(6, 63, "3f00"); testDecode(6, 63 + 1, "3f01"); testDecode(6, 63 + 0x7e, "3f7e"); testDecode(6, 63 + 0x7f, "3f7f"); testDecode(6, 63 + 0x80, "3f8001"); testDecode(6, 63 + 0x81, "3f8101"); testDecode(6, 63 + 0x7f + 0x80 * 0x01, "3fFf01"); testDecode(6, 63 + 0x00 + 0x80 * 0x02, "3f8002"); testDecode(6, 63 + 0x01 + 0x80 * 0x02, "3f8102"); testDecode(6, 63 + 0x7f + 0x80 * 0x7f, "3fFf7f"); testDecode(6, 63 + 0x00 + 0x80 * 0x80, "3f808001"); testDecode(6, 63 + 0x7f + 0x80 * 0x80 * 0x7f, "3fFf807f"); testDecode(6, 63 + 0x00 + 0x80 * 0x80 * 0x80, "3f80808001"); testDecode(8, 0, "00"); testDecode(8, 1, "01"); testDecode(8, 128, "80"); testDecode(8, 254, "Fe"); testDecode(8, 255, "Ff00"); testDecode(8, 255 + 1, "Ff01"); testDecode(8, 255 + 0x7e, "Ff7e"); testDecode(8, 255 + 0x7f, "Ff7f"); testDecode(8, 255 + 0x80, "Ff8001"); testDecode(8, 255 + 0x00 + 0x80 * 0x80, "Ff808001"); }
@Test void testDecodeExampleD_1_1() { ByteBuffer buf = ByteBuffer.wrap(TypeUtils.fromHexString("77EaFF")); buf.position(2); assertEquals(10, NBitInteger.decode(buf, 5)); }
@Test void testDecodeExampleD_1_2() { ByteBuffer buf = ByteBuffer.wrap(TypeUtils.fromHexString("881f9a0aff")); buf.position(2); assertEquals(1337, NBitInteger.decode(buf, 5)); }
@Test void testDecodeExampleD_1_3() { ByteBuffer buf = ByteBuffer.wrap(TypeUtils.fromHexString("882aFf")); buf.position(1); assertEquals(42, NBitInteger.decode(buf, 8)); }