简体   繁体   中英

Printing binary values in Java

Why the output of this java program is 8 and 9 while we try to print 010 and 011 respectively:

public class Test{
   public static void main(String str[]){ 
      System.out.println(011); 
   }
}

What is the reason?

010 is interpretetion of 10 in octal base which is 8 . And similarly 011 is interpretetion of 11 in octal base which is 9 .

Prepending an integer with 0 makes it interpreted in octal base .

Similarly, you can try printing 0x10 , which is a hexadecimal representation, and will give you 16 as output.

In Java, the default conversion from integer to string is base 10. If you want a different radix, you have to specify it explicitly. For instance, you can convert an integer value to a binary string using:

Integer.toString(value, 2);

Similarly, you can convert it to an octal value with:

Integer.toString(value, 8);

Unless the value is 0, the string will not have a leading zero. If you want a leading 0, you'll have to prepend it. Alternatively, you can format it with String.format() and specify zero fill and a minimum width for the converted string:

String.format("%1$03o", value); // the "1$ in the format string is optional here

PS It's not clear from your question what the exact problem is. It sounds like it's that you are converting from an integer value to a string. However, if the problem is that you're trying to read the string "011" and it is being read as the integer value 9, this is because a leading 0 forces interpretation as an octal value. You'll have to read it as a String value and then explicitly specify the conversion from string to integer to be base 10:

int val = Integer.valueOf(stringValue, 10);

- If you want to convert the integer to binary data, use toBinaryString() method.

Eg:

int i = 8;
Integer.toBinaryString(i);

bec. when you start your number with 0 JVM convert the number from decimal to octal that's all ;)
"11 in decimal = 9 in octal" decimal 0 1 2 3 4 5 6 7 8 9 octal 0 1 2 3 4 5 6 7 10 11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM