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?

assylias
  • 321,522
  • 82
  • 660
  • 783
Sergiu
  • 2,502
  • 6
  • 35
  • 57

3 Answers3

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
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
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.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
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

Alexandre Santos
  • 8,170
  • 10
  • 42
  • 64
  • 1
    That is because the value int -907729766 is actually the long value 3387237530. Try this: long l = 3387237530L; System.out.println((int)l); – Alexandre Santos May 08 '14 at 20:59
  • @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). – Pshemo May 09 '14 at 16:54
  • Sure, but System.out.println((int)l) doesn't print the binary, it prints with the overflow. – Alexandre Santos May 09 '14 at 18:14