如何将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, 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);
}
没有找到相关结果
已邀请:
4 个回复
瞧叮
版画
字节是正确的,并重现相同的值。 重建BigInteger的方式存在错误。您假设Java通常使用大端字节序时,字节序列化是小端字节序。http://en.wikipedia.org/wiki/Endianness
珊畴炮贩号
苏髓骗撩
僻朵庙惩竣