如何解决如何将Java BigDecimal转换为普通字节数组不是2的补码
|| 如何将大整数转换为非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
[Update2]
这是我运行的测试,可以正常工作。不知道它是否没有错误,但看起来还不错。
@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,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
, 尝试将数字拆分为字节,方法是在每次迭代中除以256,然后使用余数,然后将所有这些字节放入数组中。
, 2补码中正数的符号位为0
因此带符号或无符号对正数没有影响
, 如果该值小于long的大小,则使用longValue,然后将long切成字节。如果该值大于一个长整数,则可能需要使用迭代方法,将该数字重复除以256,将余数作为下一个字节,然后重复直到得到零。字节将从右到左生成。带符号的数字需要考虑(生成2s补码结果),但并不复杂。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。