Moj*_*bye 3 java type-conversion
我试图将包含使用C#应用程序生成的数据的输入缓冲区(字节数组)转换为java数据类型.我对C#的DecimaldataType 有一些问题.
C#示例:
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);
Run Code Online (Sandbox Code Playgroud)
但是Decimaljava中没有(也没有Decimal(int [] bits)构造函数).
在Java中,你会使用BigDecimal.这种类型并不完全相同,但它相当接近.
您只需要将96位整数重建为a BigInteger,然后对其进行缩放并选择否定它:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
20.20
Run Code Online (Sandbox Code Playgroud)
构造BigInteger零件时的屏蔽是有效地将值视为无符号 - 执行按位AND,long其中顶部32位清零且底部32位设置,我们构造的是您通过投射获得的相同数值每个int都uint在C#中.
| 归档时间: |
|
| 查看次数: |
1114 次 |
| 最近记录: |