简体   繁体   中英

How to convert int [] to Big Integer?

我想转换一个整数数组,值原来是字节。

First, make sure you know in which format your int[] is meant to be interpreted.

Each int can be seen as consisting of four bytes, and these bytes together can be converted to an BigInteger. The details are the byte order - which byte is the most and which one the least significant?

Also, do you have a signed or unsigned number?

A simple way to convert your int s to byte s (for latter use in a BigInteger constructor) would be to use ByteBuffer and wrap an IntBuffer around it.

public BigInteger toBigInteger(int[] data) {
    byte[] array = new byte[data.length * 4];
    ByteBuffer bbuf = ByteBuffer.wrap(array);
    IntBuffer ibuf = bbuf.asIntBuffer();
    ibuf.put(data);
    return new BigInteger(array);
}

Obvious adaptions would be to set the byte order of bbuf , or use another BigInteger constructor (for unsigned).

Well, what about new BigInteger(byte[] val) ?

To quote the API docs I linked to:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM