简体   繁体   English

怎么把int []转换成Big Integer?

[英]How to convert int [] to Big Integer?

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

First, make sure you know in which format your int[] is meant to be interpreted. 首先,请确保您知道int[]将以哪种格式解释。

Each int can be seen as consisting of four bytes, and these bytes together can be converted to an BigInteger. 每个int可以看作由四个字节组成,并且这些字节可以一起转换为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. int转换为byte s(供以后在BigInteger构造函数中使用)的一种简单方法是使用ByteBuffer并在其周围包装一个IntBuffer。

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). 明显的调整是设置bbuf的字节顺序,或使用另一个BigInteger构造函数(用于无符号)。

Well, what about new BigInteger(byte[] val) ? 好吧,关于新的BigInteger(byte [] val)呢?

To quote the API docs I linked to: 引用我链接到的API文档:

Translates a byte array containing the two's-complement binary representation of a BigInteger into a BigInteger. 将包含BigInteger的二进制补码二进制表示形式的字节数组转换为BigInteger。 The input array is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element. 假定输入数组为大端字节序:最高有效字节在第零个元素中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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