javabytebiginteger

BigInteger to byte[]


I need to convert a Java BigInteger instance to its value in bytes. From the API, I get this method toByteArray(), that returns a byte[] containing the two's-complement representation of this BigInteger.

Since all my numbers are positive 128 bits (16 bytes) integer, I don't need the 2's-complement form that give me 128 bits + sign bit (129 bits)...

Is there a way to get the standard (without the 2's-complement form) representation directly from a BigInteger?

If not, how can I right shift the whole byte[17] array to lose the sign bit in order to get a byte[16] array?


Solution

  • You don't have to shift at all. The sign bit is the most significant (= leftmost) bit of your byte array. Since you know your numbers will always be positive, it is guaranteed to be 0. However, the array as a whole is right-aligned.

    So there are two cases: your left-most byte is 0x00 or not. If it is 0x00 you can safely drop it:

    byte[] array = bigInteger.toByteArray();
    if (array[0] == 0) {
        byte[] tmp = new byte[array.length - 1];
        System.arraycopy(array, 1, tmp, 0, tmp.length);
        array = tmp;
    }
    

    If it is not 0, then you cannot drop it - but your array will already be in the representation you want, so you don't have to do anything.

    The above code should work for both cases.