Java-将二进制解析为long [英] Java - parse binary to long
问题描述
我有一个数字的二进制表示形式,想将其转换为long(我有Java 8)
I have a binary represenation of a number and want to convert it to long (I have Java 8)
public class TestLongs {
public static void main(String[] args){
String a = Long.toBinaryString(Long.parseLong("-1")); // 1111111111111111111111111111111111111111111111111111111111111111
System.out.println(a);
System.out.println(Long.parseLong(a, 2));// ??? but Long.parseUnsignedLong(a, 2) works
}
}
此代码导致Exception in thread "main" java.lang.NumberFormatException: For input string: "1111111111111111111111111111111111111111111111111111111111111111"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
1111111111111111111111111111111111111111111111111111111111111111
at java.lang.Long.parseLong(Long.java:592)
这是怎么了为什么Long.parseLong(a,2)不起作用?
This code results in Exception in thread "main" java.lang.NumberFormatException: For input string: "1111111111111111111111111111111111111111111111111111111111111111"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
1111111111111111111111111111111111111111111111111111111111111111
at java.lang.Long.parseLong(Long.java:592)
What is wrong here? Why Long.parseLong(a, 2) doesn't work?
推荐答案
Long.parseLong()
不会将第一个'1'字符视为符号位,因此该数字将解析为2 ^ 64-1,这也是如此对于long
而言较大. Long.parseLong()
期望代表负数的输入String
以'-'开头.
Long.parseLong()
doesn't treat the first '1' character as a sign bit, so the number is parsed as 2^64-1, which is too large for long
. Long.parseLong()
expects input String
s that represent negative numbers to start with '-'.
为了使Long.parseLong(str,2)
返回-1
,您应该向其传递一个以'-'开头并以1
的二进制表示形式-即Long.parseLong("-1",2)
的String
.
In order for Long.parseLong(str,2)
To return -1
, you should pass to it a String
that start with '-' and ends with the binary representation of 1
- i.e. Long.parseLong("-1",2)
.
这篇关于Java-将二进制解析为long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!