gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:14:35 25 4
gpt4 key购买 nike

如何将大整数转换为非 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com