Octal To Decimal Conversion Program In Java
Octal to decimal conversion is a common task in computer science, often encountered when working with different number systems. Understanding how to convert between these bases is fundamental for many programming scenarios. In this article, you will learn how to convert an octal number to its decimal equivalent using Java.
Problem Statement
The problem is to take an octal number as input and convert it into its corresponding decimal representation. Octal numbers use a base of 8, meaning they only use digits from 0 to 7. Decimal numbers, on the other hand, use a base of 10.
Example
If the input octal number is 17, the decimal equivalent is 15.
Background & Knowledge Prerequisites
To understand this conversion, you should be familiar with:
- Number Systems: Basic understanding of octal (base-8) and decimal (base-10) number systems.
- Java Basics:
- Variables and data types (e.g.,
int,String). - Input/Output operations using
Scanner. - Loops (e.g.,
whileloop). - Arithmetic operators (e.g.,
%,/,*,+). - The
Math.pow()method for calculating powers.
Use Cases or Case Studies
- Low-Level Programming: When dealing with hardware registers or memory addresses that are sometimes represented in octal.
- File Permissions (Unix/Linux): Octal numbers are frequently used to represent file permissions (e.g.,
chmod 755). Converting these to decimal can help in understanding their numeric value. - Data Representation: In some legacy systems or specific data formats, numbers might be stored or displayed in octal.
- Educational Purposes: A classic problem for learning about number system conversions and basic algorithm design.
Solution Approaches
We will explore a common and straightforward approach to convert an octal number to a decimal number.
Approach 1: Iterative Conversion using Powers of 8
This approach involves iterating through the digits of the octal number from right to left, multiplying each digit by the appropriate power of 8, and summing the results.
One-line summary
Iterate through the octal digits, multiplying each by increasing powers of 8 and accumulating the sum.Code example
// Octal to Decimal Conversion
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt the user to enter an octal number
System.out.print("Enter an octal number: ");
String octalString = scanner.nextLine();
// Step 3: Initialize variables for decimal equivalent and power of 8
int decimal = 0;
int power = 0;
// Step 4: Iterate through the octal string from right to left
for (int i = octalString.length() - 1; i >= 0; i--) {
// Step 5: Get the current digit as a character
char digitChar = octalString.charAt(i);
// Step 6: Convert the character digit to an integer
// Subtract '0' to get the integer value of the digit
int digit = digitChar - '0';
// Step 7: Check if the digit is valid for an octal number (0-7)
if (digit < 0 || digit > 7) {
System.out.println("Invalid octal number. Digits must be between 0 and 7.");
scanner.close();
return; // Exit the program if invalid
}
// Step 8: Calculate the decimal equivalent for the current digit
// digit * (8 ^ power)
decimal += digit * Math.pow(8, power);
// Step 9: Increment the power for the next digit
power++;
}
// Step 10: Print the resulting decimal number
System.out.println("Decimal equivalent: " + decimal);
// Step 11: Close the scanner to prevent resource leaks
scanner.close();
}
}
Sample output
Enter an octal number: 17
Decimal equivalent: 15
Enter an octal number: 20
Decimal equivalent: 16
Enter an octal number: 377
Decimal equivalent: 255
Stepwise explanation for clarity
- Input: The program first takes an octal number as a
Stringfrom the user. Using aStringallows us to easily access individual digits. - Initialization:
-
decimalis initialized to0. This variable will store the final decimal equivalent. -
poweris initialized to0. This variable keeps track of the current power of 8 (8^0, 8^1, 8^2, etc.).
- Iteration: A
forloop iterates through the octal string from right to left (from the least significant digit to the most significant digit).
-
octalString.length() - 1gives the index of the last character. -
i >= 0ensures all characters are processed. -
i--moves to the previous character in each iteration.
- Extract Digit:
octalString.charAt(i)gets the character at the current index. - Convert Character to Integer:
digitChar - '0'converts the character digit (e.g., '1') into its integer equivalent (e.g., 1). This works because character codes for '0' through '9' are consecutive. - Validate Digit: An
ifcondition checks if the extracteddigitis between 0 and 7. If not, it's an invalid octal number, and the program exits. - Calculate Decimal Value: The core conversion happens here:
decimal += digit * Math.pow(8, power);.
-
Math.pow(8, power)calculates 8 raised to the currentpower. - This result is multiplied by the
digit. - This product is added to the
decimalaccumulator.
- Increment Power:
power++increments thepowerfor the next digit. For the rightmost digit,poweris 0 (8^0 = 1). For the next digit to its left,poweris