Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 910
Vishnu Avatar asked Oct 22 '18 09:10

Vishnu


1 Answers

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;
}
  • First, use toByteArray() to get a byte array
  • calculate the next multiple of eight for the array length
  • If this number is not identical to the length, you need padding
    • allocate an array of the required size
    • fill the padding with -1 (sign extension) when negative (it already has the required zeros in the other case)
    • copy the original bytes

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.

like image 131
Holger Avatar answered Sep 29 '22 08:09

Holger