javajava-8bigintegerdata-conversionkmip

Convert Big Integer value to eight bit bytes(2s complement big endian) sequence which is multiple of 8 in Java


How to convert big integer to the following byte array form in Java:

Big Integers are encoded as a sequence of eight-bit bytes, in two's complement notation, transmitted big-endian. If the length of the sequence is not a multiple of eight bytes, then Big Integers SHALL be padded with the minimal number of leading sign-extended bytes to make the length a multiple of eight bytes.

This is to be in terms with KMIP protocol, section 9.1.1.4 Item Value


Solution

  • As far as I know, there is no padding functionality provided by the BigInteger API, so you have to do the padding yourself:

    For a BigInteger bigInt, use

    byte[] array = bigInt.toByteArray();
    int len = array.length, len8 = len+7 & ~7;
    if(len != len8) {
        int pad = len8 - len;
        byte[] nArray = new byte[len8];
        if(bigInt.signum() < 0) Arrays.fill(nArray, 0, pad, (byte)-1);
        System.arraycopy(array, 0, nArray, pad, len);
        array = nArray;
    }
    

    Note that a sign extended padded array still is compatible to the BigInteger(byte[]) constructor, so an assert bigInt.equals(new BigInteger(array)); after the operation should never fail.