Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - parse binary to long [duplicate]

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?

like image 556
android_dev Avatar asked Oct 18 '16 10:10

android_dev


2 Answers

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

like image 57
Eran Avatar answered Oct 30 '22 21:10

Eran


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

System.out.println(new BigInteger(a, 2).longValue());
like image 40
ΦXocę 웃 Пepeúpa ツ Avatar answered Oct 30 '22 22:10

ΦXocę 웃 Пepeúpa ツ