簡體   English   中英

Java - 將解析和無符號十六進制字符串轉換為帶符號的long

[英]Java - parse and unsigned hex string into a signed long

我有一堆十六進制字符串,其中一個,例如:

  d1bc4f7154ac9edb

這是十六進制值“-3333702275990511909”。 如果你做Long.toHexString(“d1bc4f7154ac9edb”),這是你得到的相同的十六進制;

現在,讓我們假設我只能訪問十六進制字符串值,就是這樣。 這樣做:

  Long.parseLong(hexstring, 16);

不起作用,因為它將它轉換為對Long來說太大的不同值。 是否可以將這些無符號十六進制值轉換為有符號長整數?

謝謝!

你可以使用BigInteger來解析它並獲得一個long

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

您可以將其拆分為一半,一次讀取32位。 然后使用shift-left by 32和邏輯或將其恢復為單個long。

先前的答案過於復雜或過時。

Long.parseUnsignedLong(hexstring, 16)

下面的方法的好處是每次需要時都不會創建另一個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM