Java BigDecimal's negative fraction to binary form

213 Views Asked by At

I need advice how to properly convert negative fractional part to binary. My custom data type with fixed point need be converted to 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? How one can distinquish "plain -1" from negative fraction? Short generic case example would be very usefull.

How one will write -1.375 and -0.375 in binary ?

1

There are 1 best solutions below

5
On

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.