Home > database >  Java BigInteger toByteArray specify number of bytes to use
Java BigInteger toByteArray specify number of bytes to use

Time:02-06

I was wondering it there is any way to specify how many bytes to use when creating the byte array using toByteArray method. For example:

BigInteger bigInteger = new BigInteger("-12");

I want bigInteger.toByteArray() to return an array with values FF and F4 (assuming that the value is represented using 4 bytes - short variable, but it returns only F4.

CodePudding user response:

You could just make your own helper class.

public class BigIntegerHelper {

    public static byte[] toByteArray(BigInteger big, int minLength) {
        byte[] base=big.toByteArray();
        byte[] returnArray=new byte[Math.max(base.length, minLength)];
        if ((base[0]&128)!=0) {
            Arrays.fill(returnArray, (byte) 0xFF);
        }
        System.arraycopy(base,0,returnArray,returnArray.length-base.length,base.length);
        return returnArray;
    }

}

CodePudding user response:

It's unclear exactly what you're going for but BigInteger has a shortValue() method that might help.

For example,

BigInteger big = new BigInteger("-12");
short s = big.shortValue();
byte [] bytes = ByteBuffer.allocate(2).putShort(s).array();

Something similar can be done if you want 4 bytes (int) or 8 bytes(long).

  •  Tags:  
  • Related