Converting between octal and decimal numbers is a fundamental skill in computer programming.
In this tutorial, we’ll show you how to write a Java program to convert octal numbers to decimal and vice-versa.
Octal Number to Decimal Conversion
An octal number is a base-8 number system that uses eight digits, namely 0, 1, 2, 3, 4, 5, 6, and 7.
To convert an octal number to a decimal number, you can use the following formula:
decimal = sum(oi * 8i), i=0 to n-1
where oi is the ith digit of the octal number, n is the number of digits in the octal number, and the exponent i increases from 0 to n-1.
Here’s a Java program that converts an octal number to a decimal number:
import java.util.Scanner; public class OctalToDecimal { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an octal number: "); String octal = input.nextLine(); int decimal = 0; for (int i = 0; i < octal.length(); i++) { int digit = octal.charAt(i) - '0'; decimal += digit * Math.pow(8, octal.length() - i - 1); } System.out.println("Decimal equivalent: " + decimal); } }
This program prompts the user to enter an octal number and uses a loop to calculate its decimal equivalent using the formula mentioned above.
Finally, it prints the decimal equivalent to the console.
Decimal to Octal Conversion
A decimal number is a base-10 number system that uses ten digits, namely 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
To convert a decimal number to an octal number, you can use the following algorithm:
- Divide the decimal number by 8
- Record the remainder
- Divide the quotient by 8
- Record the remainder
- Repeat steps 3 and 4 until the quotient becomes 0
- The octal number is the sequence of remainders in reverse order
Here’s a Java program that converts a decimal number to an octal number:
import java.util.Scanner; public class DecimalToOctal { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a decimal number: "); int decimal = input.nextInt(); String octal = ""; while (decimal != 0) { int remainder = decimal % 8; octal = remainder + octal; decimal /= 8; } System.out.println("Octal equivalent: " + octal); } }
This program prompts the user to enter a decimal number and uses a loop to calculate its octal equivalent using the algorithm mentioned above.
Finally, it prints the octal equivalent to the console.
Conclusion
In this tutorial, we’ve shown you how to write a Java program to convert octal numbers to decimal and vice-versa.
By understanding the formulas and algorithms involved, you can easily extend these programs to handle other number systems as well.