7

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?

0

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

11 Comments

then what is difference between Long.parseLong and Long.parseUnsignedLong? does "Unsigned" refer to binary represenation or long value??
@android_dev parseUnsignedLong expects to treat the long value as if it was unsigned.
Long.parseUnsignedLong treats the output long as an unsigned value, so when you treat a long value as unsigned, the max possible value becomes 2^64-1 (represented by 64 1 bits), which is why a String of 64 1s is acceptable. @android_dev
@android_dev parseUnsignedInt parses large unsigned values. long is still signed and no method changes that. You can treat as if it was unsigned of course.
@android_dev long is still signed, so when you print Long.parseUnsignedLong("11111111111111111‌​11111111111111111111‌​11111111111111111111‌​1111111", 2)) you see -1. In order to see this number as an unsigned long, you need to print it with the static method Long.toUnsignedString().
|
3

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.