[英]How to convert a hexadecimal string to long in java?
I want to convert a hex string to long in java. 我想在Java中将十六进制字符串转换为long。
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? 有什么办法在Java中将String转换为long吗? Or am i trying which is not really possible!! 还是我正在尝试这是不可能的!
Thanks! 谢谢!
Long.decode(str)
accepts a variety of formats: Long.decode(str)
接受多种格式:
Accepts decimal, hexadecimal, and octal numbers given by the following grammar: 接受以下语法给出的十进制,十六进制和八进制数字:
DecodableString: DecodableString:
- Sign opt DecimalNumeral 签名选择十进制数字
- Sign opt 0x HexDigits 选择opt 0x HexDigits
- Sign opt 0X HexDigits 选择opt 0X HexDigits
- Sign opt # HexDigits 选择 #HexDigits登录
- Sign opt 0 OctalDigits 签名选择 0 OctalDigits
Sign: 标志:
- - --
But in your case that won't help, your String is beyond the scope of what long can hold. 但是,如果这对您没有帮助,则您的String超出了可以容纳的范围。 You need a BigInteger
: 您需要一个BigInteger
:
String s = "4d0d08ada45f9dde1e99cad9";
BigInteger bi = new BigInteger(s, 16);
System.out.println(bi);
Output: 输出:
23846102773961507302322850521 23846102773961507302322850521
For Comparison, here's Long.MAX_VALUE
: 为了进行比较,这是Long.MAX_VALUE
:
9223372036854775807 9223372036854775807
使用parseLong:
Long.parseLong(s, 16)
new BigInteger(string, 16).longValue()
For any value of someLong: 对于someLong的任何值:
new BigInteger(Long.toHexString(someLong), 16).longValue() == someLong
In other words, this will return the long
you sent into Long.toHexString()
for any long
value, including negative numbers. 换句话说,这将返回long
你送入Long.toHexString()
对于任何long
价值,包括负数。 It will also accept strings that are bigger than a long
and silently return the lower 64 bits of the string as a long
. 它也将接受比一个更大的弦long
,默默字符串的低64位返回为long
。 You can just check the string length <= 16 (after trimming whitespace) if you need to be sure the input fits in a long
. 如果需要确保输入适合long
则只需检查字符串长度<= 16(在修剪空格之后)。
Long.parseLong(s, 16)
will only work up to "7fffffffffffffff"
. Long.parseLong(s, 16)
仅适用于"7fffffffffffffff"
。 Use BigInteger
instead: 改用BigInteger
:
public static boolean isHex(String hex) {
try {
new BigInteger(hex, 16);
return true;
} catch (NumberFormatException e) {
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.