我有一个代表2的补码数的十六进制字符串。有没有一种简单的方法(库/函数)将十六进制转换为十进制而不直接使用它的位?
E.G。这是左边的十六进制给出的预期输出:
"0000" => 0
"7FFF" => 32767 (max positive number)
"8000" => -32768 (max negative number)
"FFFF" => -1
谢谢!
答案 0 :(得分:19)
这似乎欺骗java转换数字而不强制结果:
Integer.valueOf("FFFF",16).shortValue(); // evaluates to -1 (short)
当然这种东西只适用于8,16,32和64位2的补码:
Short.valueOf("FF",16).byteValue(); // -1 (byte)
Integer.valueOf("FFFF",16).shortValue(); // -1 (short)
Long.valueOf("FFFFFFFF",16).intValue(); // -1 (int)
new BigInteger("FFFFFFFFFFFFFFFF",16).longValue(); // -1 (long)
答案 1 :(得分:8)
只需写一个实用工具方法:
public static Integer twosComp(String str) throws java.lang.Exception {
Integer num = Integer.valueOf(str, 16);
return (num > 32767) ? num - 65536 : num;
}
试验:
twosComp("7FFF") -> 32767
twosComp("8000") -> -32768
twosComp("FFFF") -> -1
答案 2 :(得分:3)
这似乎运作得相当好。它可以通过传递非标准长度字符串来欺骗:“FFF”映射到-1。零填充将纠正错误。
你不清楚你想要什么类型的回报,所以我已经以适当的大小返回Number
。
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;
}
示例输出:
"33" -> 51
"FB" -> -5
"3333" -> 13107
"FFFC" -> -4
"33333333" -> 53687091
"FFFFFFFD" -> -3
"3333333333333333" -> 3689348814741910323
"FFFFFFFFFFFFFFFE" -> -2
"33333333333333333333" -> 241785163922925834941235
"FFFFFFFFFFFFFFFFFFFF" -> -1