我有一个十六进制字符串,表示2的补码数。是否有一种简单的方法(库/函数)将十六进制转换为十进制而不直接使用其位??
如这是给定左边十六进制的预期输出:
"0000" => 0
"7FFF" => 32767 (max positive number)
"8000" => -32768 (max negative number)
"FFFF" => -1
谢谢!
这似乎欺骗了java,使其在不强制得到正结果的情况下转换数字:
Integer.valueOf("FFFF",16).shortValue(); // evaluates to -1 (short)
当然,这类事情只适用于8、16、32和64位的补位:
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)
例子。
写一个实用程序方法:
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
这似乎工作得相当好。它可以通过传递非标准长度的字符串来欺骗它:"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