/** * Encodes a BigInteger {@code value} such that unsigned byte order comparison * is consistent with {@link BigInteger#compareTo(BigInteger)}. This also sign-extends * the value to {@code bigIntSize} bytes if necessary: useful to create a fixed-width size. * @see #sortableBytesToBigInt(byte[], int, int) */ public static void bigIntToSortableBytes(BigInteger bigInt, int bigIntSize, byte[] result, int offset) { byte[] bigIntBytes = bigInt.toByteArray(); byte[] fullBigIntBytes; if (bigIntBytes.length < bigIntSize) { fullBigIntBytes = new byte[bigIntSize]; System.arraycopy(bigIntBytes, 0, fullBigIntBytes, bigIntSize-bigIntBytes.length, bigIntBytes.length); if ((bigIntBytes[0] & 0x80) != 0) { // sign extend Arrays.fill(fullBigIntBytes, 0, bigIntSize-bigIntBytes.length, (byte) 0xff); } } else if (bigIntBytes.length == bigIntSize) { fullBigIntBytes = bigIntBytes; } else { throw new IllegalArgumentException("BigInteger: " + bigInt + " requires more than " + bigIntSize + " bytes storage"); } // Flip the sign bit so negative bigints sort before positive bigints: fullBigIntBytes[0] ^= 0x80; System.arraycopy(fullBigIntBytes, 0, result, offset, bigIntSize); assert sortableBytesToBigInt(result, offset, bigIntSize).equals(bigInt): "bigInt=" + bigInt + " converted=" + sortableBytesToBigInt(result, offset, bigIntSize); }
/** Decode single BigInteger dimension */ public static BigInteger decodeDimension(byte value[], int offset) { return NumericUtils.sortableBytesToBigInt(value, offset, BYTES); }
/** * Encodes a BigInteger {@code value} such that unsigned byte order comparison * is consistent with {@link BigInteger#compareTo(BigInteger)}. This also sign-extends * the value to {@code bigIntSize} bytes if necessary: useful to create a fixed-width size. * @see #sortableBytesToBigInt(byte[], int, int) */ public static void bigIntToSortableBytes(BigInteger bigInt, int bigIntSize, byte[] result, int offset) { byte[] bigIntBytes = bigInt.toByteArray(); byte[] fullBigIntBytes; if (bigIntBytes.length < bigIntSize) { fullBigIntBytes = new byte[bigIntSize]; System.arraycopy(bigIntBytes, 0, fullBigIntBytes, bigIntSize-bigIntBytes.length, bigIntBytes.length); if ((bigIntBytes[0] & 0x80) != 0) { // sign extend Arrays.fill(fullBigIntBytes, 0, bigIntSize-bigIntBytes.length, (byte) 0xff); } } else if (bigIntBytes.length == bigIntSize) { fullBigIntBytes = bigIntBytes; } else { throw new IllegalArgumentException("BigInteger: " + bigInt + " requires more than " + bigIntSize + " bytes storage"); } // Flip the sign bit so negative bigints sort before positive bigints: fullBigIntBytes[0] ^= 0x80; System.arraycopy(fullBigIntBytes, 0, result, offset, bigIntSize); assert sortableBytesToBigInt(result, offset, bigIntSize).equals(bigInt): "bigInt=" + bigInt + " converted=" + sortableBytesToBigInt(result, offset, bigIntSize); }