Convert arbitrary byte [] size to BigInteger [] and then safely convert back to exactly the same byte [], any hints?

I believe that converting exactly to BigInteger [] would be optimal in my case. Has anyone done or found it written in Java and ready to share?

So imagine that I have an arbitrary size byte[] = {0xff,0x3e,0x12,0x45,0x1d,0x11,0x2a,0x80,0x81,0x45,0x1d,0x11,0x2a,0x80,0x81} How to convert it to an array BigInteger and then restore its original byte array?

ty in advance.

+4
source share
1 answer

Use BigInteger.toByteArray () and BigInteger (byte []) .

According to javadoc, the last ...

Translates an array of bytes containing the binary representation of the BigInteger binary complement into BigInteger. It is assumed that the input array is in byte order of a large byte: the most significant byte is in the null element.

If your byte-like representation is different, you may need to apply some additional conversions.

EDIT - if you need to keep leading (i.e. non-essential) zeros, follow these steps:

  • When converting from a byte array to BigInteger, also pay attention to the size of the byte array. This information is not encoded in the value of BigInteger.

  • When converting from BigInteger to a byte array, sign-expand the byte array to the same length as the original byte array.

EDIT 2 - if you want to turn an array of bytes into an array of BigIntegers with no more than N bytes in each of them, you need to create a temporary array of size N, repeatedly 1) fill it with bytes from the array of input bytes (with the rest of the addition at the end) and 2) uses it to create BigInteger values ​​using the constructor above. Maybe 20 lines of code?

But I'm frankly puzzled that you (apparently) are choosing a value for N based on memory usage, and not based on the mathematical algorithm that you are trying to implement.

+7
source

Source: https://habr.com/ru/post/1304985/


All Articles