Developer Resources
Programming Binary Conversions.
Learn how to perform binary-to-decimal and binary-to-octal conversions programmatically in Python and Java using standard built-ins and custom algorithms.
Binary conversions in Python.
Python makes number conversions simple with built-in functions like int(), oct(), and hex().
binary_to_decimal.py
# Method 1: Using built-in int() with base 2
binary_str = "10101"
decimal_val = int(binary_str, 2)
print(f"Decimal (built-in): {decimal_val}") # Output: 21
# Method 2: Manual Positional Notation algorithm
def binary_to_decimal_manual(b_str):
decimal = 0
for i, digit in enumerate(reversed(b_str)):
if digit == '1':
decimal += 2 ** i
return decimal
print(f"Decimal (manual): {binary_to_decimal_manual('10101')}") # Output: 21 binary_to_octal.py
# Convert binary to octal in Python
binary_str = "11010110"
# Step 1: Convert binary to decimal
decimal_val = int(binary_str, 2)
# Step 2: Convert decimal to octal using oct()
octal_str = oct(decimal_val)[2:] # Stripping the '0o' prefix
print(f"Octal: {octal_str}") # Output: 326 Binary conversions in Java.
In Java, we utilize the static utility methods on the wrapper class Integer, specifically Integer.parseInt() and Integer.toOctalString().
BinaryConversions.java
public class BinaryConversions {
public static void main(String[] args) {
String binaryStr = "10101";
// 1. Binary to Decimal
int decimalVal = Integer.parseInt(binaryStr, 2);
System.out.println("Decimal: " + decimalVal); // Output: 21
// 2. Binary to Octal
String octalStr = Integer.toOctalString(decimalVal);
System.out.println("Octal: " + octalStr); // Output: 25 (octal of 21)
}
}