java中的2的补码hex数到十进制数

我有一个hex字符串代表一个2的补数。 是否有一种简单的方法(库/函数)将hex转换为十进制而不直接使用它的位?

EG这是左侧hex给出的预期输出:

"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位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) 

这里的例子 。

只需写一个实用工具方法:

  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