且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在java中将十六进制字符串转换为long?

更新时间:2023-11-15 19:53:58

Long.decode(str) 接受多种格式:


接受十进制,十六进制,以及由以下
语法给出的八进制
数字:

DecodableString:


  • 签名 opt DecimalNumeral

  • Sign opt 0x HexDigits

  • Sign opt 0X HexDigits
  • Sign opt #HexDigits

  • Sign opt 0 OctalDigits
  • >


签名:


  • -


但是在你的情况下,这并不会起作用,你的字符串已经超出了长期持有的范围。您需要 BigInteger

  String s =4d0d08ada45f9dde1e99cad9; 
BigInteger bi = new BigInteger(s,16);
System.out.println(bi);

输出:


23846102773961507302322850521


对于比较,这里是 Long .MAX_VALUE


9223372036854775807



I want to convert a hex string to long in java.

I have tried with general conversion.

String s = "4d0d08ada45f9dde1e99cad9";
long l = Long.valueOf(s).longValue();
System.out.println(l);
String ls = Long.toString(l);

But I am getting this error message:

java.lang.NumberFormatException: For input string: "4d0d08ada45f9dde1e99cad9"

Is there any way to convert String to long in java? Or am i trying which is not really possible!!

Thanks!

Long.decode(str) accepts a variety of formats:

Accepts decimal, hexadecimal, and octal numbers given by the following grammar:
DecodableString:

  • Signopt DecimalNumeral
  • Signopt 0x HexDigits
  • Signopt 0X HexDigits
  • Signopt # HexDigits
  • Signopt 0 OctalDigits

Sign:

  • -

But in your case that won't help, your String is beyond the scope of what long can hold. You need a BigInteger:

String s = "4d0d08ada45f9dde1e99cad9";
BigInteger bi = new BigInteger(s, 16);
System.out.println(bi);

Output:

23846102773961507302322850521

For Comparison, here's Long.MAX_VALUE:

9223372036854775807