Java Program To Convert Octal Number To Decimal And Vice Versa
Octal and decimal are two fundamental number systems in computing. Understanding how to convert between them is crucial for tasks ranging from low-level programming to data representation.
In this article, you will learn how to convert octal numbers to decimal and decimal numbers to octal using various Java programming approaches.
Problem Statement
The problem involves translating numerical values between the octal (base-8) and decimal (base-10) number systems. Octal numbers use digits 0-7, while decimal numbers use 0-9. Since computers internally process binary, and octal provides a more compact representation than binary (three binary digits map to one octal digit), conversions are often necessary when working with permissions (e.g., Linux file permissions), memory addresses, or specific data formats that utilize an octal base.
Example
Consider the following conversion examples:
- Octal to Decimal: The octal number
17(base 8) is equivalent to15(base 10). - (1 * 8^1) + (7 * 8^0) = 8 + 7 = 15
- Decimal to Octal: The decimal number
25(base 10) is equivalent to31(base 8). - 25 / 8 = 3 remainder 1
- 3 / 8 = 0 remainder 3
- Reading remainders from bottom to top: 31
Background & Knowledge Prerequisites
To effectively understand and implement these conversions in Java, you should be familiar with:
- Basic Java Syntax: Variables, data types (
int,String), loops (while,for), conditional statements. - Number Systems: Basic understanding of decimal (base-10), binary (base-2), and octal (base-8) systems.
- Arithmetic Operators: Modulo (
%), division (/), multiplication (*), addition (+). - Math Class Methods: Specifically
Math.pow()for exponentiation. -
ScannerClass: For reading user input. -
IntegerClass Methods:parseInt(),toOctalString().
Use Cases or Case Studies
Converting between octal and decimal numbers has several practical applications:
- File Permissions (Unix/Linux): File permissions are often represented in octal (e.g.,
755,644). Converting these to decimal can be useful for human-readable interpretation or when integrating with systems that prefer decimal values. - Embedded Systems Programming: Some microcontrollers or older systems might use octal for addressing memory locations or configuring registers, making conversions necessary for debugging or programming.
- Data Representation: Certain legacy data formats or specialized protocols might use octal encoding for specific values, requiring conversion for processing or display.
- Network Protocols: While less common than hexadecimal, some low-level network configurations or specific protocol fields might occasionally use octal representations.
- Educational Purposes: Understanding these conversions helps solidify the fundamental concepts of number systems, which is a cornerstone of computer science education.
Solution Approaches
We will explore different methods to convert numbers between octal and decimal, including manual calculation and built-in Java functions.
Approach 1: Octal to Decimal Conversion
Method 1: Manual Calculation (Loop-based)
This approach involves iterating through the digits of the octal number, multiplying each digit by the appropriate power of 8, and summing the results.
// Octal to Decimal (Manual)
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Prompt user for an octal number
System.out.print("Enter an octal number: ");
int octalNumber = scanner.nextInt();
// Step 2: Initialize decimal value and power
int decimalNumber = 0;
int power = 0; // Represents 8^0, 8^1, 8^2, etc.
int tempOctalNumber = octalNumber; // Use a temporary variable for calculation
// Step 3: Loop through each digit of the octal number
while (tempOctalNumber != 0) {
// Get the last digit of the octal number
int digit = tempOctalNumber % 10;
// Add the decimal equivalent of the digit to the total
// digit * (8 ^ power)
decimalNumber += digit * Math.pow(8, power);
// Remove the last digit from the octal number
tempOctalNumber /= 10;
// Increment the power for the next digit
power++;
}
// Step 4: Display the result
System.out.println("Decimal equivalent: " + decimalNumber);
scanner.close();
}
}
Sample Output:
Enter an octal number: 17
Decimal equivalent: 15
Stepwise Explanation:
- Input: The program takes an octal number as integer input (e.g.,
17). Note that17here is treated as a sequence of digits1and7, not the decimal value seventeen. - Initialization:
decimalNumberis set to0, andpower(for 8's exponent) is set to0. A temporary variabletempOctalNumberholds the input octal number to avoid modifying the original. - Iteration: A
whileloop continues as long astempOctalNumberis not0.
-
digit = tempOctalNumber % 10;: Extracts the rightmost digit of thetempOctalNumber. For17, it first gets7, then1. -
decimalNumber += digit * Math.pow(8, power);: Multiplies the extracteddigitby8raised to the currentpowerand adds it todecimalNumber. -
tempOctalNumber /= 10;: Removes the rightmost digit fromtempOctalNumber. -
power++;: Incrementspowerfor the next digit's calculation.
- Result: Once the loop finishes,
decimalNumberholds the decimal equivalent, which is then printed.
Method 2: Using Integer.parseInt()
Java's Integer class provides a convenient method parseInt(String s, int radix) which directly converts a string representation of a number in a specified base to its decimal integer equivalent.
// Octal to Decimal (Built-in)
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Prompt user for an octal number as a string
System.out.print("Enter an octal number: ");
String octalString = scanner.next();
// Step 2: Use Integer.parseInt() with radix 8
// The second argument '8' specifies that the input string is an octal number.
int decimalNumber = Integer.parseInt(octalString, 8);
// Step 3: Display the result
System.out.println("Decimal equivalent: " + decimalNumber);
scanner.close();
}
}
Sample Output:
Enter an octal number: 17
Decimal equivalent: 15
Stepwise Explanation:
- Input: The program takes the octal number as a
Stringinput. This is important becauseparseInt()expects a string. - Conversion:
Integer.parseInt(octalString, 8)performs the conversion. The8indicates that theoctalStringis in base-8. - Result: The resulting
decimalNumberis printed. This method is generally preferred for its simplicity and robustness against invalid octal digits (it will throw aNumberFormatExceptionifoctalStringcontains digits8or9).
Approach 2: Decimal to Octal Conversion
Method 1: Manual Calculation (Loop-based)
This method involves repeatedly dividing the decimal number by 8 and collecting the remainders. The octal number is formed by reading the remainders in reverse order.
// Decimal to Octal (Manual)
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Prompt user for a decimal number
System.out.print("Enter a decimal number: ");
int decimalNumber = scanner.nextInt();
// Step 2: Initialize octal value and multiplier
int octalNumber = 0;
int i = 1; // Multiplier to place remainders at correct positions (1, 10, 100, etc.)
int tempDecimalNumber = decimalNumber; // Use a temporary variable for calculation
// Step 3: Loop until the decimal number becomes 0
while (tempDecimalNumber != 0) {
// Get the remainder when divided by 8
int remainder = tempDecimalNumber % 8;
// Add the remainder to the octal number, multiplied by its place value
octalNumber += remainder * i;
// Divide the decimal number by 8
tempDecimalNumber /= 8;
// Multiply 'i' by 10 to shift position for the next remainder
i *= 10;
}
// Step 4: Display the result
System.out.println("Octal equivalent: " + octalNumber);
scanner.close();
}
}
Sample Output:
Enter a decimal number: 25
Octal equivalent: 31
Stepwise Explanation:
- Input: The program takes a decimal number as integer input (e.g.,
25). - Initialization:
octalNumberis set to0, andi(a multiplier for constructing the octal number) is set to1.tempDecimalNumberstores the original decimal number for calculations. - Iteration: A
whileloop continues as long astempDecimalNumberis not0.
-
remainder = tempDecimalNumber % 8;: Calculates the remainder whentempDecimalNumberis divided by8. This is the next octal digit. -
octalNumber += remainder * i;: Adds theremainder(octal digit) tooctalNumber, adjusted byito place it in the correct decimal position (e.g., 1s, 10s, 100s place in the *decimal representation* of the octal number). -
tempDecimalNumber /= 8;: DividestempDecimalNumberby8. -
i *= 10;: Multipliesiby10to prepare for the next remainder, which will be at the next "place value" in the resulting octal number (as a decimal representation).
- Result: Once the loop finishes,
octalNumberholds the decimal representation of the octal equivalent, which is then printed.
Method 2: Using Integer.toOctalString()
Java provides a direct method toOctalString(int i) in the Integer class, which converts a decimal integer to its octal string representation.
// Decimal to Octal (Built-in)
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Prompt user for a decimal number
System.out.print("Enter a decimal number: ");
int decimalNumber = scanner.nextInt();
// Step 2: Use Integer.toOctalString()
// This method directly converts the decimal integer to its octal string representation.
String octalString = Integer.toOctalString(decimalNumber);
// Step 3: Display the result
System.out.println("Octal equivalent: " + octalString);
scanner.close();
}
}
Sample Output:
Enter a decimal number: 25
Octal equivalent: 31
Stepwise Explanation:
- Input: The program takes a decimal number as an
intinput. - Conversion:
Integer.toOctalString(decimalNumber)directly converts theintto its octal string form. - Result: The resulting
octalStringis printed. This is the most straightforward and recommended method for decimal to octal conversion in Java.
Conclusion
Converting between octal and decimal number systems is a fundamental skill in programming and computer science. Java offers flexible ways to perform these conversions. For manual control and a deeper understanding of the underlying logic, loop-based arithmetic methods are effective. For efficiency, conciseness, and robustness, the built-in Integer class methods (parseInt() with radix 8 and toOctalString()) are highly recommended.
Summary
- Octal to Decimal:
- Manual: Repeatedly extract the rightmost digit, multiply by powers of 8 (
8^0,8^1,8^2, ...), and sum the results. - Built-in: Use
Integer.parseInt(octalString, 8)for a concise and robust conversion. - Decimal to Octal:
- Manual: Repeatedly divide the decimal number by 8, collect the remainders, and read them in reverse order to form the octal number.
- Built-in: Use
Integer.toOctalString(decimalNumber)for a straightforward and efficient conversion. - Understanding these conversions is valuable for tasks involving file permissions, memory addressing, and data representation in various computing contexts.