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

标签 java binary bigdecimal

如何将大整数转换为非 2 的补码格式的字节数组。基本上我只需要转换正数,不需要符号位。

所以像 10 这样的东西会变成字节 0x0a 即-> 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;
}

我得到的输出值是 -19720446 和//int val = (int) b & 0xFF;未注释并用作加数,我得到值 4292024066

[更新2] 这是我运行的测试。不确定它是否没有错误,但看起来不错。

@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);
}

最佳答案

差异主要是概念上的。无符号数在 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);

打印

[2, 23, -45, -1]
35116031

字节正确并重现相同的值。

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

关于java - 如何将 java BigDecimal 转换为普通字节数组(不是 2 的补码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6167697/

相关文章:

java - BigDecimal 到 Java/Android 上 BigDecimal 的强大功能

java - 如何在 MigLayout 中获得一个向右对齐的按钮

java - "link with editor"功能在 Eclipse 中有什么作用?

java - 每次我从 HIbernate 检索一个实体然后丢弃时,Hibernate 是否会挂起任何资源

java - 一元 "~"运算符 - 这里到底发生了什么?

Java - 如何将字符串转换为货币格式的大十进制

java - 将正则表达式从 java 转换为 .Net

javascript - 将二进制 NodeJS 缓冲区转换为 JavaScript ArrayBuffer

python - 如何在 python 2.7 中打印 1 的最大连续出现次数?

java - java中大十进制精度零是什么意思