BigInteger到byte
我需要将Java BigInteger实例转换为以字节为单位的值。 从API中,我得到了这个方法toByteArray()
,它返回一个包含这个BigInteger的二进制补码表示的byte []。
由于我的所有数字都是正128位(16字节)整数,所以我不需要2位补码forms给我128位+符号位(129位)……
有没有办法直接从BigInteger获得标准(没有二进制补码forms)表示?
如果没有,我怎么能正确移位整个byte [17]数组以丢失符号位以获得一个byte [16]数组?
你根本不需要转移。 符号位是字节数组中最重要的(=最左边)位。 由于您知道您的数字将始终为正数,因此保证为0.但是,整个数组是右对齐的。
所以有两种情况:你最左边的字节是0x00。 如果是0x00,你可以安全地删除它:
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,那么你不能删除它 – 但你的数组已经在你想要的表示中,所以你不必做任何事情。
上述代码应适用于这两种情况。
字节数组中的第一个(最重要的)字节可能不仅包含符号位,还包含正常位。
比如这个BigInteger:
new BigInteger("512") .add(new BigInteger("16")) .add(new BigInteger("1"));
有这种位模式:00000010 00010001
也就是说,顶部字节(带符号位)也有正常的位,正如您所期望的那样。
那么,你想要什么回来?
00000010 00010001 (what you have) or 00000100 0010001? or 10000100 01??????
你可以复制掉第一个字节。 或者你可以忽略它。
BigInteger bi = BigInteger.ONE.shiftLeft(127); byte[] bytes1 = bi.toByteArray(); System.out.println(Arrays.toString(bytes1)); byte[] bytes = new byte[bytes1.length-1]; System.arraycopy(bytes1, 1, bytes, 0, bytes.length); System.out.println(Arrays.toString(bytes));