Java BigDecimal, C # Equivalent Decimal (int [] bits) Constructor

I am trying to convert an input buffer (byte array) containing data generated by a C # application to java data types. I have a problem with C # Decimal

dataType.

C # example:

decimal decimalValue = 20.20M;
//converting a Decimal value to 4 integer vlaues
int[] intPieces= Decimal.GetBits(decimalValue); //{2020,0,0,131072}
//using native constructor to rebuild value
Decimal newDecimalValue = new decimal(intPieces); //20.20
Console.WriteLine("DecimalValue is " + newDecimalValue);

      

but there is no constructor in java Decimal

(nor Decimal (int [] bits)).

C # Decimal constructor (Int32 []) documention.

+3


source to share


1 answer


In Java, you have to use BigDecimal

. It's not exactly the same type, but it's close enough.

You just need to reconstruct the 96 bit integer as BigInteger

, then scale it and refute it:

import java.math.BigDecimal;
import java.math.BigInteger;

public class Test {

    public static void main(String[] args) {
        int[] parts = { 2020, 0, 0, 131072 };
        BigInteger integer = BigInteger.valueOf(parts[2] & 0xffffffffL).shiftLeft(32)
            .add(BigInteger.valueOf(parts[1] & 0xffffffffL )).shiftLeft(32)
            .add(BigInteger.valueOf(parts[0] & 0xffffffffL));        
        BigDecimal decimal = new BigDecimal(integer, (parts[3] & 0xff0000) >> 16);
        if (parts[3] < 0) // Bit 31 set
        {
            decimal = decimal.negate();
        }
        System.out.println(decimal);
    }
}

      



Output:

20.20

      

Escaping when constructing parts BigInteger

allows values ​​to be effectively treated as unsigned - doing a bitwise AND with long

the upper 32 bits and the lower 32 bits set, we create you get the same numeric value every time you click int

on uint

in C #.

+5


source







All Articles