Java - parse binary to long [duplicate]

旧时模样 提交于 2021-02-07 13:14:14

问题


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
}

}

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?


回答1:


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 Strings that represent negative numbers to start with '-'.

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).




回答2:


Eran is right, and the answer to your question is:

System.out.println(new BigInteger(a, 2).longValue());


来源:https://stackoverflow.com/questions/40106229/java-parse-binary-to-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!