byte []的任意大小转换为BigInteger的[],然后安全地转换回一模一样的byte [],任何线索?转换为、线索、大小、安全

2023-09-11 06:23:07 作者:Figure(背影)

我认为完全转化为BigInteger的[]将是最佳的在我的情况。任何人做了或发现了这个用Java编写的,并愿意分享?

I believe conversion exactly to BigInteger[] would be optimal in my case. Anyone had done or found this written in Java and willing to share?

所以,想象我有一个任意大小字节[] = {0xFF的,0x3E的,0x​​12,0x45,0x1d,0x11,0x2a,0x80,0x81,0x45,0x1d,0x11,0x2a,0x80,0x81} 我该如何将它转换为BigInteger的的数组,然后才能安全地恢复回原来的字节数组?

So imagine I have arbitrary size byte[] = {0xff,0x3e,0x12,0x45,0x1d,0x11,0x2a,0x80,0x81,0x45,0x1d,0x11,0x2a,0x80,0x81} How do I convert it to array of BigInteger's and then be able to recover it back the original byte array safely?

TY提前。

推荐答案

使用的 BigInteger.toByteArray()和的的BigInteger(byte []的)。

据javadoc的,后者...

According to the javadoc, the latter ...

平移包含二进制补码二进制重新presentation一个BigInteger成一个BigInteger的字节数组。输入数组假定为big-endian字节顺序:最显著字节在第零个元素。

Translates a byte array containing the two's-complement binary representation of a BigInteger into a BigInteger. The input array is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element.

如果您的字节方式重新presentation不同的是,您可能需要应用一些额外的转换。

If your byte-wise representation is different, you may need to apply some extra transformations.

修改 - 如果你需要preserve领先的(即非显著)零点,请执行以下操作:

EDIT - if you need to preserve leading (i.e. non-significant) zeros, do the following:

在从字节数组转换为BigInteger,还记下字节数组的大小。此信息不连接codeD中的BigInteger值。 JAVA中怎么把int型数据转为BigInteger型数据

When you convert from the byte array to a BigInteger, also make a note of the size of the byte array. This information is not encoded in the BigInteger value.

当您从BigInteger值转换为字节数组,符号扩展字节数组出相同长度的原始字节数组。

When you convert from the BigInteger to a byte array, sign-extend the byte array out to the same length as the original byte array.

编辑2 - 如果你想打开一个字节数组到BigIntegers阵列与在每一个最N个字节,你需要创建一个大小为N临时数组,反复1)填写它从输入字节数组(左填充底)和2),用它来创建使用上述构造的BigInteger值。也许20行code?

EDIT 2 - if you want to turn a byte array into an array of BigIntegers with at most N bytes in each one, you need to create a temporary array of size N, repeatedly 1) fill it with bytes from the input byte array (with left padding at the end) and 2) use it to create BigInteger values using the constructor above. Maybe 20 lines of code?

但我坦率地感到困惑,你会(显然)挑 N 基于内存的使用,而不是根据你正在努力实现的数学算法的值。

But I'm frankly baffled that you would (apparently) pick a value for N based on memory usage rather than based on the mathematical algorithm you are trying to implement.