Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing binary values in Java

Tags:

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?

like image 998
Praveen Avatar asked Sep 18 '26 18:09

Praveen


2 Answers

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

P.S. 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);
like image 200
Ted Hopp Avatar answered Sep 21 '26 07:09

Ted Hopp


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.

like image 45
Rohit Jain Avatar answered Sep 21 '26 08:09

Rohit Jain