NBitInteger { public static void encode(ByteBuffer buf, int n, int i) { if (n == 8) { if (i < 0xFF) { buf.put((byte) i); } else { buf.put((byte) 0xFF); int length = i - 0xFF; while (true) { if ((length & ~0x7F) == 0) { buf.put((byte) length); return; } else { buf.put((byte) ((length & 0x7F) | 0x80)); length >>>= 7; } } } } else { int p = buf.position() - 1; int bits = 0xFF >>> (8 - n); if (i < bits) { buf.put(p, (byte) ((buf.get(p) & ~bits) | i)); } else { buf.put(p, (byte) (buf.get(p) | bits)); int length = i - bits; while (true) { if ((length & ~0x7F) == 0) { buf.put((byte) length); return; } else { buf.put((byte) ((length & 0x7F) | 0x80)); length >>>= 7; } } } } }  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 testEncode() { testEncode(6, 0, "00"); testEncode(6, 1, "01"); testEncode(6, 62, "3e"); testEncode(6, 63, "3f00"); testEncode(6, 63 + 1, "3f01"); testEncode(6, 63 + 0x7e, "3f7e"); testEncode(6, 63 + 0x7f, "3f7f"); testEncode(6, 63 + 0x00 + 0x80 * 0x01, "3f8001"); testEncode(6, 63 + 0x01 + 0x80 * 0x01, "3f8101"); testEncode(6, 63 + 0x7f + 0x80 * 0x01, "3fFf01"); testEncode(6, 63 + 0x00 + 0x80 * 0x02, "3f8002"); testEncode(6, 63 + 0x01 + 0x80 * 0x02, "3f8102"); testEncode(6, 63 + 0x7f + 0x80 * 0x7f, "3fFf7f"); testEncode(6, 63 + 0x00 + 0x80 * 0x80, "3f808001"); testEncode(6, 63 + 0x7f + 0x80 * 0x80 * 0x7f, "3fFf807f"); testEncode(6, 63 + 0x00 + 0x80 * 0x80 * 0x80, "3f80808001"); testEncode(8, 0, "00"); testEncode(8, 1, "01"); testEncode(8, 128, "80"); testEncode(8, 254, "Fe"); testEncode(8, 255, "Ff00"); testEncode(8, 255 + 1, "Ff01"); testEncode(8, 255 + 0x7e, "Ff7e"); testEncode(8, 255 + 0x7f, "Ff7f"); testEncode(8, 255 + 0x80, "Ff8001"); testEncode(8, 255 + 0x00 + 0x80 * 0x80, "Ff808001"); }
@Test void testEncodeExampleD_1_1() { ByteBuffer buf = ByteBuffer.allocate(16); buf.put((byte) 0x77); buf.put((byte) 0xFF); NBitInteger.encode(buf, 5, 10); buf.flip(); String r = TypeUtils.toHexString(BufferUtils.toArray(buf)); assertEquals("77Ea", r); }
@Test void testEncodeExampleD_1_2() { ByteBuffer buf = ByteBuffer.allocate(16); buf.put((byte) 0x88); buf.put((byte) 0x00); NBitInteger.encode(buf, 5, 1337); buf.flip(); String r = TypeUtils.toHexString(BufferUtils.toArray(buf)); assertEquals("881f9a0a", r); }
@Test void testEncodeExampleD_1_3() { ByteBuffer buf = ByteBuffer.allocate(16); buf.put((byte) 0x88); buf.put((byte) 0xFF); NBitInteger.encode(buf, 8, 42); buf.flip(); String r = TypeUtils.toHexString(BufferUtils.toArray(buf)); assertEquals("88Ff2a", r); }