NBitInteger { public static int octectsNeeded(int n, int i) { if (n == 8) { int nbits = 0xFF; i = i - nbits; if (i < 0) return 1; if (i == 0) return 2; int lz = Integer.numberOfLeadingZeros(i); int log = 32 - lz; return 1 + (log + 6) / 7; } int nbits = 0xFF >>> (8 - n); i = i - nbits; if (i < 0) return 0; if (i == 0) return 1; int lz = Integer.numberOfLeadingZeros(i); int log = 32 - lz; return (log + 6) / 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 testOctetsNeeded() { assertEquals(0, NBitInteger.octectsNeeded(5, 10)); assertEquals(2, NBitInteger.octectsNeeded(5, 1337)); assertEquals(1, NBitInteger.octectsNeeded(8, 42)); assertEquals(3, NBitInteger.octectsNeeded(8, 1337)); assertEquals(0, NBitInteger.octectsNeeded(6, 62)); assertEquals(1, NBitInteger.octectsNeeded(6, 63)); assertEquals(1, NBitInteger.octectsNeeded(6, 64)); assertEquals(2, NBitInteger.octectsNeeded(6, 63 + 0x00 + 0x80 * 0x01)); assertEquals(3, NBitInteger.octectsNeeded(6, 63 + 0x00 + 0x80 * 0x80)); assertEquals(4, NBitInteger.octectsNeeded(6, 63 + 0x00 + 0x80 * 0x80 * 0x80)); }