开发者

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

开发者 https://www.devze.com 2022-12-25 00:21 出处:网络
I believe conversion exactly to BigInteger[] would be optimal in my case. Anyone had done or found this written in Java and wi开发者_StackOverflow中文版lling to share?

I believe conversion exactly to BigInteger[] would be optimal in my case. Anyone had done or found this written in Java and wi开发者_StackOverflow中文版lling to share?

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 in advance.


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

According to the javadoc, the latter ...

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.

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

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

  1. 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.

  2. 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.

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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号