In this example, you will learn to convert any binary number to octal number. The user will ask to enter a binary number and converts it into an octal number.
1 2 |
Enter a binary number: 1110 Octal number: 16 |
Example: Convert Binary Number to Octal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.Scanner; public class Bin2oct { public static void main(String[] args) { int binary; int rem; int decimal = 0; int octal = 0; int i = 1; Scanner scan = new Scanner(System.in); System.out.print("Enter a binary number: "); binary = scan.nextInt(); /*convert binary to decimal number first*/ while(binary != 0) { rem = binary % 10; decimal = decimal +(rem * i); binary = binary / 10; i = i * 2; } /*Then convert decimal to octal number*/ i = 1; while(decimal != 0) { rem = decimal % 8; octal = octal +(rem * i); decimal = decimal / 8; i = i * 10; } System.out.print("Octal number: "+octal); } } |
1 2 |
Enter a Binary Number: 1110 Hexadecimal value: 69 |