2

I have this binary value :

11001001111001010010010010011010.

In java 7, if I declare:

int value = 0b11001001111001010010010010011010;

and print the value I get -907729766.

How can I achieve this in Java 6 as well?

4

3 Answers 3

6

You have to parse it as a long first, then narrow it into int.

String s = "11001001111001010010010010011010";
int i = (int)Long.parseLong(s, 2); //2 = binary
System.out.println(i);

Prints:

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

Comments

1

Just so you know since Java 8 there is Integer.parseUnsignedInt method which lets you parse your data without problems

String s = "11001001111001010010010010011010";
System.out.println(Integer.parseUnsignedInt(s,2));

Output: -907729766

Java is open source so you should be able to find this methods code and adapt it to your needs in Java 6.

Comments

0

You can't use the value you entered, because it is outside of the limit of Integer. Use the radix 2 to convert it on Java 6.

This will fail

    System.out.println(Integer.parseInt("11001001111001010010010010011010", 2));

with Exception in thread "main" java.lang.NumberFormatException: For input string: "11001001111001010010010010011010" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:495) at Test.main(Test.java:7)

But this will work

 System.out.println(Long.parseLong("11001001111001010010010010011010", 2));

the output will be 3387237530

3 Comments

That is because the value int -907729766 is actually the long value 3387237530. Try this: long l = 3387237530L; System.out.println((int)l);
@AlexandreSantos Not exactly. Decimal value of int -907729766 is same as decimal value of long -907729766L. It binary representation of int -907729766 is same as binary representation of long 3387237530L (at least at last 32 bits).
Sure, but System.out.println((int)l) doesn't print the binary, it prints with the overflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.