Java – 将解析和无符号hex字符串转换为带符号的long

我有一堆hex字符串,其中之一,例如:

d1bc4f7154ac9edb 

这是hex值“-3333702275990511909”。 如果你做Long.toHexString(“d1bc4f7154ac9edb”),你就得到了相同的hex数;

现在,让我们假设我只能访问hex字符串值,就是这样。 这样做:

  Long.parseLong(hexstring, 16); 

不起作用,因为它将它转换为对Long而言太大的不同值。 是否可以将这些无符号hex值转换为有符号长整数?

谢谢!

你可以使用BigInteger来解析它并获得一个long

 long value = new BigInteger("d1bc4f7154ac9edb", 16).longValue(); System.out.println(value); // this outputs -3333702275990511909 

您可以将其分成两半,一次读取32位。 然后使用shift-left 32和逻辑或将其恢复为单个long。

下面的方法的好处是每次需要时都不会创建另一个BigInteger对象。

 public class Test { /** * Returns a {@code long} containing the least-significant 64 bits of the unsigned hexadecimal input. * * @param valueInUnsignedHex a {@link String} containing the value in unsigned hexadecimal notation * @return a {@code long} containing the least-significant 64 bits of the value * @throws NumberFormatException if the input {@link String} is empty or contains any nonhexadecimal characters */ public static final long fromUnsignedHex(final String valueInUnsignedHex) { long value = 0; final int hexLength = valueInUnsignedHex.length(); if (hexLength == 0) throw new NumberFormatException("For input string: \"\""); for (int i = Math.max(0, hexLength - 16); i < hexLength; i++) { final char ch = valueInUnsignedHex.charAt(i); if (ch >= '0' && ch <= '9') value = (value << 4) | (ch - '0' ); else if (ch >= 'A' && ch <= 'F') value = (value << 4) | (ch - ('A' - 0xaL)); else if (ch >= 'a' && ch <= 'f') value = (value << 4) | (ch - ('a' - 0xaL)); else throw new NumberFormatException("For input string: \"" + valueInUnsignedHex + "\""); } return value; } public static void main(String[] args) { System.out.println(fromUnsignedHex("d1bc4f7154ac9edb")); } } 

这产生了

 -3333702275990511909 

先前的答案过于复杂或过时。

Long.parseUnsignedLong(hexstring, 16)