如何将java BigDecimal转换为普通字节数组(不是2的补码)

Abe*_*Abe 4 java binary bigdecimal

如何从大整数转换为不是2的补码格式的字节数组.基本上我只需转换正数而不需要符号位.

所以像10这样的东西会变成字节0x0a ie-> 00001010

[更新] 根据评论我试过这个

public void testBinary()
{
    BigDecimal test = new BigDecimal(35116031);
    BigInteger theInt = test.unscaledValue();
    byte[] arr = theInt.toByteArray();
    System.out.println(getCounterVal(arr, new BigInteger("256")));
}
public BigInteger getCounterVal(byte[] arr, BigInteger multiplier)
{
    BigInteger counter = BigInteger.ZERO;
    for(int i = (arr.length - 1); i >=0; i--)
    {
        int b = arr[i];
        //int val = (int) b & 0xFF;
        BigInteger augend = BigInteger.valueOf(b);
        counter = counter.add(augend.multiply(multiplier.pow(i)));
    }
    return counter;
}
Run Code Online (Sandbox Code Playgroud)

我得到的输出值是-19720446并且使用// int val =(int)b&0xFF; 取消注释并用作augend,我的值为4292024066

[Update2] 这是我运行的测试.不确定它是否没有bug但看起来很好.

@Test
public void bigIntegerToArray()
{
    BigInteger bigInt = new BigInteger("35116444");
    byte[] array = bigInt.toByteArray();
    if (array[0] == 0)
    {
        byte[] tmp = new byte[array.length - 1];
        System.arraycopy(array, 1, tmp, 0, tmp.length);
        array = tmp;
    }

    BigInteger derived = BigInteger.ZERO;
    BigInteger twofiftysix = new BigInteger("256");
    int j = 0;
    for (int i = array.length - 1; i >= 0; i--)
    {
        int val = (int) array[i] & 0xFF;
        BigInteger addend = BigInteger.valueOf(val);
        BigInteger multiplier = twofiftysix.pow(j);
        addend = addend.multiply(multiplier);
        derived = derived.add(addend);
        j++;
    }

    Assert.assertEquals(bigInt, derived);
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*rey 12

差异主要是概念上的.无符号数字与2的赞美相同.2的赞美只是描述了如何表示你说你没有的负数.

即10是00001010,有签名和无符号表示.

要从BigDecimal或BigInteger获取字节,您可以使用它提供的方法.

BigDecimal test = new BigDecimal(35116031);
BigInteger theInt = test.unscaledValue();
byte[] arr = theInt.toByteArray();
System.out.println(Arrays.toString(arr));

BigInteger bi2 = new BigInteger(arr);
BigDecimal bd2 = new BigDecimal(bi2, 0);
System.out.println(bd2);
Run Code Online (Sandbox Code Playgroud)

版画

[2, 23, -45, -1]
35116031
Run Code Online (Sandbox Code Playgroud)

字节是正确的并重现相同的值.

重建BigInteger的方式存在一个错误.当Java通常使用大端语时,您假设字节序列化是小端的http://en.wikipedia.org/wiki/Endianness