BigInteger到byte [] [英] BigInteger to byte[]

查看:181
本文介绍了BigInteger到byte []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要转换Java BigInteger 实例到其以字节为单位的值。在API中,我得到了这个方法 toByteArray(),它返回一个包含此BigInteger的二进制补码表示的byte []。

I need to convert a Java BigInteger instance to its value in bytes. From the API, I get this method toByteArray(), that returns a byte[] containing the two's-complement representation of this BigInteger.

因为我的所有数字都是正128位(16字节)整数,所以我不需要2位补码形式给我128位+符号位(129位)......

Since all my numbers are positive 128 bits (16 bytes) integer, I don't need the 2's-complement form that give me 128 bits + sign bit (129 bits)...

有没有办法直接从BigInteger获得标准(没有2的补码形式)?

Is there a way to get the standard (without the 2's-complement form) representation directly from a BigInteger?

如果没有,我如何右移整个字节[17]数组以丢失符号位以获得一个字节[16]数组?

If not, how can I right shift the whole byte[17] array to lose the sign bit in order to get a byte[16] array?

推荐答案

你根本不需要换班。符号位是字节数组中最重要的(=最左边)位。因为你知道你的数字总是正数,所以它保证为0.但是,数组整体是右对齐的。

You don't have to shift at all. The sign bit is the most significant (= leftmost) bit of your byte array. Since you know your numbers will always be positive, it is guaranteed to be 0. However, the array as a whole is right-aligned.

所以有两种情况:你最左边的字节是不是0x00。如果是0x00,你可以安全地删除它:

So there are two cases: your left-most byte is 0x00 or not. If it is 0x00 you can safely drop it:

byte[] array = bigInteger.toByteArray();
if (array[0] == 0) {
    byte[] tmp = new byte[array.length - 1];
    System.arraycopy(array, 1, tmp, 0, tmp.length);
    array = tmp;
}

如果它不是0,那么你不能放弃它 - 但是你的阵列将会已经在你想要的表示中,所以你不必做任何事情。

If it is not 0, then you cannot drop it - but your array will already be in the representation you want, so you don't have to do anything.

以上代码适用于这两种情况。

The above code should work for both cases.

这篇关于BigInteger到byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆