How to convert java BigDecimal to normal byte array (not 2's complement)

拥有回忆 提交于 2019-12-05 16:46:41

The difference is largely conceptual. Unsigned numbers are the same in 2's compliment. 2's compliment just describes how to represent negative numbers which you say you don't have.

i.e. 10 is 00001010 in signed and unsigned representation.

To get the bytes from a BigDecimal or BigInteger you can use the methods it provides.

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

prints

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

The bytes are correct and reproduce the same value.

There is a bug in the way you rebuild your BigInteger. You assume the byte serialization is little endian when Java typically uses big endian http://en.wikipedia.org/wiki/Endianness

Try to split the number in bytes, by dividing by 256 in each iteration and using the remainder, and place all these bytes into an array.

the sign bit in 2-compliment for positive numbers is 0

so signed or unsigned doesn't make a difference for positive numbers

If the value is less than the size of a long then use longValue, then chop the long into bytes. If the value is bigger than a long then probably you need to use an iterative approach, repeatedly dividing the number by 256, taking the remainder as the next byte, then repeating until you get zero. The bytes would be generated right to left. Signed numbers require thought (to generate 2s-complement results) but aren't much more complicated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!