0

我正在尝试使用with将 aLargeInteger转换为byte[]长度未知的 abitLength()

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;
}

但执行人返回

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

指向y.toByteArray(in, 0);.

如何in正确设置长度?

(注释的代码是转换后的BigInteger代码留下的。)

4

1 回答 1

2

toByteArray 的 javadoc 告诉你

java.lang.IndexOutOfBoundsException - 如果 bytes.length < (bitLength() >> 3) + 1

因此应该是>= (bitLength() >> 3) + 1

您所做的几乎相同,只是您没有添加 1。

所以(int)Math.ceil((double)y.bitLength() / 8.0) -1

但更容易使用文档版本 y.(bitLength() >> 3) + 1

于 2014-01-22T18:04:23.283 回答