问题
I have a number of type BigDecimal, for example 18446744073709551616, and I want to convert it to hexadecimal value. I'm fine with truncating the fractional portion.
Is there a way to do this instead of doing it manually?
回答1:
Judging by your example you should use BigInteger
instead of BigDecimal
. This way you could use
new BigInteger("18446744073709551616").toString(16)
If you can't change type of original object convert it to BigInteger later in method
new BigDecimal("18446744073709551616").toBigInteger().toString(16);
回答2:
Take into account that converting a decimal value into hex requires an exponent. You could get the hexadecimal String representing a numeric value using Formatter.
%A : The result is formatted as a hexadecimal floating-point number with a significand and an exponent
%X: The result is formatted as a hexadecimal integer
Use the %A
conversion if you want to convert a decimal value:
System.out.println(String.format("%A", myBigDecimal));
Curiously, the code above is correct regarding the javadoc for Formatter
, but there seems to be a related 9-year-old error in the javadocs, that has been fixed a few weeks ago in Java 8: 5035569 : (fmt) assertion error in Formatter for BigDecimal and %a. You can use the analog code below:
System.out.println(String.format("%A", myBigDecimal.doubleValue()));
EDIT
Judging by the value in your post, you don't really care about the fractional part. You could use the %X
conversion in the pattern and just provide the BigInteger
representation:
BigDecimal bd = new BigDecimal("18446744073709551616");
System.out.println(String.format("%X", bd.toBigInteger()));
回答3:
Theoretically it is possible to represent BigDecimal as a hex string, simiolar to Double.toHexString
0x1.199999999999p+1
but AFAIK there is no standard way to do it and custom implementation will not be easy
来源:https://stackoverflow.com/questions/15615800/how-to-convert-only-the-integer-part-of-a-bigdecimal-to-hex-string