In this tutorial, we will see how to convert a binary number to an octal number with the help of examples.
Java binary to octal conversion example
To convert a binary number to octal number, we can use the Integer.toOctalString() method, which takes binary number as an argument and returns a string which is the octal equivalent of the passed binary number.
Here we have given a binary number in form of a String, we are first converting the string to a base 2 number (binary number) using Integer.parseInt() method, we have stored the result in the integer number bnum
. We are then passing this binary number bnum
to the Integer.toOctalString() method to get the octal number.
public class JavaExample{ public static void main(String args[]){ /* To take input from user, import the java.util.Scanner * package and write the following lines * Scanner scanner = new Scanner(System.in); * System.out.println("Enter the number: "); * int bnum = Integer.parseInt(scanner.nextLine(), 2); */ String number = "10101"; int bnum = Integer.parseInt(number, 2); String ostr = Integer.toOctalString(bnum); System.out.println("Octal Value after conversion is: "+ostr); } }
Output:
As shown in the comments if we want to get the binary number from user instead of hardcoded value then we can import the java.util.Scanner
package and use the following lines of code:
Scanner scanner = new Scanner(System.in); System.out.println("Enter the number: "); int bnum = Integer.parseInt(scanner.nextLine(), 2);
Leave a Reply