Day 8: Manual Octal ↔ Decimal Conversion with Integers Only
1. Octal → Decimal (Input as int
)
public static int octalToDecimal(int octal) {
int decimal = 0;
int place = 1; // 8^0 initially
while (octal > 0) {
int digit = octal % 10; // rightmost digit (0–7)
decimal += digit * place; // add digit * current power of 8
place *= 8; // next power of 8
octal /= 10; // shift right one digit
}
return decimal;
}
// Example:
System.out.println(octalToDecimal(17)); // prints 15
How it works
-
% 10
extracts the least-significant digit of the octal number. -
place
tracks powers of 8 (1, 8, 64, ...). - Multiply digit by
place
, add to total, then update bothplace
andoctal
.
2. Decimal → Octal (Output as int
)
public static int decimalToOctal(int decimal) {
int octal = 0;
int factor = 1; // 10^0 for placing digits in decimal slots
while (decimal > 0) {
int remainder = decimal % 8; // next octal digit
octal += remainder * factor; // place digit at correct decimal position
decimal /= 8; // move to next digit in base 8
factor *= 10; // shift factor to next decimal place (10, 100, ...)
}
return octal;
}
// Example:
System.out.println(decimalToOctal(15)); // prints 17
How it works
-
% 8
gets the least-significant octal digit. - Each digit is placed in the decimal representation by multiplying by
factor
(1, 10, 100, ...). - Update
decimal
, and increasefactor
for the next digit.
3. Complete Utility Class
public class ManualBaseConverter {
public static int octalToDecimal(int octal) {
int decimal = 0;
int place = 1;
while (octal > 0) {
int digit = octal % 10;
decimal += digit * place;
place *= 8;
octal /= 10;
}
return decimal;
}
public static int decimalToOctal(int decimal) {
int octal = 0;
int factor = 1;
while (decimal > 0) {
int remainder = decimal % 8;
octal += remainder * factor;
decimal /= 8;
factor *= 10;
}
return octal;
}
public static void main(String[] args) {
System.out.println("Octal 17 → Decimal " + octalToDecimal(17));
System.out.println("Decimal 15 → Octal " + decimalToOctal(15));
}
}
Day 8 Key Takeaways
- Pure integer arithmetic: no string operations or library calls.
-
Octal → Decimal: extract digits with
%10
, accumulate using an ever‑increasingplace
multiplier of 8. -
Decimal → Octal: extract base‑8 digits with
%8
, build the octal number in decimal slots via an increasingfactor
multiplier of 10.
Top comments (0)