If you know that your BigInteger represents an unsigned 128-bit (16-byte) number, you can use the following code to modify the result of BigInteger.toByteArray:
byte[] bytes = bigInteger.toByteArray(); if (bytes.length > 16) { // length not what we expected: remove the extra leading 0 sign byte // (i.e. return the last 16 bytes of array) int nExtraBytes = bytes.length - 16; return Arrays.copyOfRange(bytes, nExtraBytes, bytes.length); } else if (bytes.length < 16) { // original array passed to the BigInteger(int signum, byte[] magnitude) // constructor must've had multiple leading 0 bytes which were ignored, // so prepend those leading 0 bytes int nMissingBytes = 16 - bytes.length; byte[] padded = new byte[16]; System.arraycopy(bytes, 0, padded, nMissingBytes, bytes.length); return padded; } return bytes;
This requires prior knowledge of the number of bytes you expect (i.e. 16 if you have a 128-bit number).
Note: this code is a modification of the original accepted answer, to correctly handle a case where the leading 0 byte must not be removed (see my comment for an example), and to also ensure that you get an array of exactly 16 bytes (which preserves all the leading 0 bits of a 128-bit number).
<<<operator in Java.