This seems to work reasonably well. It can be fooled by passing it non-standard length strings: "FFF" maps to -1. Zero padding will correct the fault.
You are not clear on what type return you want, so I have returned Number
, at whatever size is appropriate.
public Number hexToDec(String hex) {
if (hex == null) {
throw new NullPointerException("hexToDec: hex String is null.");
}
// You may want to do something different with the empty string.
if (hex.equals("")) { return Byte.valueOf("0"); }
// If you want to pad "FFF" to "0FFF" do it here.
hex = hex.toUpperCase();
// Check if high bit is set.
boolean isNegative =
hex.startsWith("8") || hex.startsWith("9") ||
hex.startsWith("A") || hex.startsWith("B") ||
hex.startsWith("C") || hex.startsWith("D") ||
hex.startsWith("E") || hex.startsWith("F");
BigInteger temp;
if (isNegative) {
// Negative number
temp = new BigInteger(hex, 16);
BigInteger subtrahend = BigInteger.ONE.shiftLeft(hex.length() * 4);
temp = temp.subtract(subtrahend);
} else {
// Positive number
temp = new BigInteger(hex, 16);
}
// Cut BigInteger down to size.
if (hex.length() <= 2) { return (Byte)temp.byteValue(); }
if (hex.length() <= 4) { return (Short)temp.shortValue(); }
if (hex.length() <= 8) { return (Integer)temp.intValue(); }
if (hex.length() <= 16) { return (Long)temp.longValue(); }
return temp;
}
Sample output:
"33" -> 51
"FB" -> -5
"3333" -> 13107
"FFFC" -> -4
"33333333" -> 53687091
"FFFFFFFD" -> -3
"3333333333333333" -> 3689348814741910323
"FFFFFFFFFFFFFFFE" -> -2
"33333333333333333333" -> 241785163922925834941235
"FFFFFFFFFFFFFFFFFFFF" -> -1