BigInteger.toByteArray()返回有目的的前导零? [英] BigInteger.toByteArray() returns purposeful leading zeros?

查看:347
本文介绍了BigInteger.toByteArray()返回有目的的前导零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将bigints转换为二进制,radix16和radix64编码,并看到神秘的msb零填充。这是一个大问题,我可以解决零填充或者做其他事情吗?

I'm transforming bigints into binary, radix16 and radix64 encoding and seeing mysterious msb zero paddings. Is this a biginteger problem that I can workaround by stripping zero padding or perhaps doing something else?

我的测试代码:

    String s;
    System.out.printf( "%s length %d\n", s = "123456789A", (new BigInteger( s, 16 )).toByteArray().length );
    System.out.printf( "%s length %d\n", s = "F23456789A", (new BigInteger( s, 16 )).toByteArray().length );

产生输出:

    123456789A length 5
    F23456789A length 6

其中较长的数组前面没有填充。在检查BigInteger.toByteArray()后,我看到:

Of which the longer array has zero padding at the front. Upon inspection of BigInteger.toByteArray() I see:

public byte[] toByteArray() {
    int byteLen = bitLength()/8 + 1;
    byte[] byteArray = new byte[byteLen];

现在,我可以找到 private int bitLength; ,但是我无法找到bitLength()的定义,以确定这个类为什么会这样做 - 也许连接到符号扩展?

Now, I can find private int bitLength;, but I can't quite find where bitLength() is defined to figure out exactly why this class does this - connected to sign extension perhaps?

推荐答案

感谢Jon Skeet的回答。这里是我用来转换的一些代码,很可能它可以被优化。

Thanks Jon Skeet for your answer. Here's some code I'm using to convert, very likely it can be optimized.

import java.math.BigInteger;
import java.util.Arrays;

public class UnsignedBigInteger {

    public static byte[] toUnsignedByteArray(BigInteger value) {
        byte[] signedValue = value.toByteArray();
        if(signedValue[0] != 0x00) {
            throw new IllegalArgumentException("value must be a psoitive BigInteger");
        }
        return Arrays.copyOfRange(signedValue, 1, signedValue.length);
    }

    public static BigInteger fromUnsignedByteArray(byte[] value) {
        byte[] signedValue = new byte[value.length + 1];
        System.arraycopy(value,  0, signedValue, 1, value.length);
        return new BigInteger(signedValue);
    }
}

这篇关于BigInteger.toByteArray()返回有目的的前导零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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