I'm trying to convert a LargeInteger
into a byte[]
of unknown length using bitLength()
with
static byte[] encodeint(LargeInteger y) {
//byte[] in = y.toByteArray();
byte[] in = new byte[(int)Math.ceil((double)y.bitLength() / 8.0)];
y.toByteArray(in, 0);
//
byte[] out = new byte[in.length];
for (int i=0;i<in.length;i++) {
out[i] = in[in.length-1-i];
}
return out;
}
but the executor returns
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
which points to y.toByteArray(in, 0);
.
How can the length of in
be properly set?
(The commented code is leftover from converted BigInteger
code.)
The javadoc for toByteArray tells you
Thus in should be
>= (bitLength() >> 3) + 1
What you have done is nearly the same except you have not added the 1.
So
(int)Math.ceil((double)y.bitLength() / 8.0) -1
but easier to use the documented version
y.(bitLength() >> 3) + 1