1

I'm trying to compare a Hexadecimal String with a Double in a conditional statement. I have converted the hex string from a byte array.

double x = (Math.pow(2, 256));
byte[] h = null;
...
String hexString = bytesToHex(h); //converts byte array to hex string
double doubleValueOfHex = Double.valueOf(hexString); //convert hex string to double

And then I want to do something like this...

if (doubleValueOfHex < x) {
...
} else {
...

I have tried converting them both to BigDecimal but I still run into problems,

For instance if i convert x and hexString to a BigDecimal

BigDecimal a = new BigDecimal(hexString);
BigDecimal b = new BigDecimal(x);

if (a < b) {
...
} else {
...

It only says the operator '<' is undefined for the argument types

Thanks for the help

javadev
  • 688
  • 2
  • 6
  • 17
Matthew
  • 57
  • 1
  • 9

1 Answers1

1

The BigDecimals are not primitives, thus you can't use '<', but they implement Comparable interface. So your code should be something like that :

if (a.compareTo(b) < 0) {
  ....
 }

See: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#compareTo(java.math.BigDecimal)

kofemann
  • 4,217
  • 1
  • 34
  • 39