[英]Java BigDecimal's negative fraction to binary form
I need advice how to properly convert negative fractional part to binary. 我需要如何将负小数部分正确转换为二进制的建议。 My custom data type with fixed point need be converted to byte[]
. 我的定点自定义数据类型需要转换为byte[]
。 So, currently I need to implement such conversion: 所以,目前我需要实现这样的转换:
BigDecimal -> byte[] -> BigDecimal
As I understand, fraction follows the same 2's complement
form as an integer part, right? 据我了解,分数遵循与整数部分相同的2's complement
形式,对吗? How one can distinquish "plain -1" from negative fraction? 如何区分负数的“普通-1”? Short generic case example would be very usefull. 简短的通用案例将非常有用。
How one will write -1.375 and -0.375 in binary ? 一个人怎么用二进制写-1.375和-0.375?
I think you can code as (updated): 我认为您可以将代码编码为(更新):
Convert to byte[] 转换为字节[]
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
BigDecimal d = BigDecimal.valueOf(-0.00390625);
dos.writeInt(d.scale());
dos.write(d.unscaledValue().toByteArray());
dos.close(); // flush
byte[] array = bos.toByteArray();
Convert from byte[] 从字节转换[]
ByteArrayInputStream bis = new ByteArrayInputStream(array);
DataInputStream dis = new DataInputStream(bis);
int sc = dis.readInt(); //grab 4 bytes
BigInteger unscaledVal = new BigInteger(Arrays.copyOfRange(array, 4, array.length));
System.out.println(new BigDecimal(unscaledVal, sc));
Note: probably you would like to save BigDecimal
array length. 注意:可能您想保存BigDecimal
数组长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.