Python Program to Convert Binary to Octal Number
oct(int(binary_string, 2))[2:] which converts the binary string to an integer and then to octal, removing the '0o' prefix.Examples
How to Think About It
Algorithm
Code
binary_str = input('Enter a binary number: ') octal_str = oct(int(binary_str, 2))[2:] print('Octal number:', octal_str)
Dry Run
Let's trace the binary number '110101' through the code
Input binary string
binary_str = '110101'
Convert binary to decimal
int('110101', 2) = 53
Convert decimal to octal string
oct(53) = '0o65'
Remove '0o' prefix
'0o65'[2:] = '65'
Print octal number
Output: Octal number: 65
| Step | Operation | Value |
|---|---|---|
| 1 | Input binary_str | 110101 |
| 2 | Convert to decimal | 53 |
| 3 | Convert to octal string | 0o65 |
| 4 | Remove prefix | 65 |
| 5 | Print output | Octal number: 65 |
Why This Works
Step 1: Convert binary string to decimal
Using int(binary_str, 2) reads the binary string as a base 2 number and converts it to a decimal integer.
Step 2: Convert decimal to octal string
The oct() function converts the decimal integer to an octal string with a '0o' prefix.
Step 3: Remove the octal prefix
Slicing with [2:] removes the '0o' prefix to get the clean octal number string.
Alternative Approaches
binary_str = input('Enter binary: ') padded = binary_str.zfill((len(binary_str)+2)//3*3) octal = '' for i in range(0, len(padded), 3): group = padded[i:i+3] octal += str(int(group, 2)) print('Octal:', octal)
binary_str = input('Enter binary: ') dec = int(binary_str, 2) octal = format(dec, 'o') print('Octal:', octal)
Complexity: O(n) time, O(n) space
Time Complexity
Converting the binary string to an integer takes O(n) time where n is the length of the binary string. Converting to octal is also O(n) in the worst case.
Space Complexity
The space used is O(n) to store the input string and the output octal string.
Which Approach is Fastest?
Using built-in functions like int() and oct() is fastest and simplest compared to manual grouping.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Built-in int() and oct() | O(n) | O(n) | Simplicity and speed |
| Manual grouping by 3 bits | O(n) | O(n) | Learning bit manipulation |
| Using format() | O(n) | O(n) | Readability and clarity |
int(binary_string, 2) to convert binary to decimal easily before converting to octal.