Here you can find the source of bigIntToSortableBytes(BigInteger bigInt, int bigIntSize, byte[] result, int offset)
public static void bigIntToSortableBytes(BigInteger bigInt, int bigIntSize, byte[] result, int offset)
//package com.java2s; /*/* ww w .j av a2 s .c o m*/ * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.math.BigInteger; import java.util.Arrays; public class Main { /** * 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); } /** * Decodes a BigInteger value previously written with {@link #bigIntToSortableBytes} * @see #bigIntToSortableBytes(BigInteger, int, byte[], int) */ public static BigInteger sortableBytesToBigInt(byte[] encoded, int offset, int length) { byte[] bigIntBytes = new byte[length]; System.arraycopy(encoded, offset, bigIntBytes, 0, length); // Flip the sign bit back to the original bigIntBytes[0] ^= 0x80; return new BigInteger(bigIntBytes); } }