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?

有帮助吗?

解决方案

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

其他提示

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.

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top