在 Java 中添加无限大小的字节数组

Adding Byte Arrays of unlimited size in Java

有没有简单的字节数组相加的方法?

我的意思是数学加法(无串联):

00 00 FF    
00 00 FF
--------
00 01 FE

我可以通过将字节数组转换为数字格式来实现,但这种方法受到数字格式最大值的限制。我需要一个可以处理比标准格式提供的值大得多的值的解决方案。

您可以使用理论上没有大小限制的 BigInteger。实际上,显然,如果字节数太大而无法放入内存,那么您需要采取不同的方法。

public void test() {
    BigInteger a = new BigInteger(new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0xff});
    BigInteger b = new BigInteger(new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0xff});

    System.out.println(a.toString(16) + "+" + b.toString(16) + "=" + a.add(b).toString(16));
}

打印 ff+ff=1fe.