convert a number from base 2 to base 8 in python

To convert a number from base 2 to base 8 in Python, we can use the following algorithm:

  1. Take the given number in base 2 as input.
  2. Starting from the rightmost digit, divide the number into groups of 3 digits each.
  3. If the digits in a group are less than 3, add leading zeros to make it a 3-digit group.
  4. Convert each 3-digit group to its equivalent decimal value.
  5. Write the decimal values obtained in step 4 in sequence to get the final converted number in base 8.

Here's the Python code that implements the above algorithm:

main.py
def base2_to_base8(n):
    # Step 1
    n = str(n)
    num_len = len(n)
    # Step 2
    groups = [n[max(0, i-3):i] for i in range(num_len, 0, -3)][::-1]
    # Step 3
    groups = [g.zfill(3) for g in groups]
    # Step 4
    decimal_values = [int(g, 2) for g in groups]
    # Step 5
    return ''.join([str(dv) for dv in decimal_values])
339 chars
13 lines

Let's test the function with an example:

main.py
binary_num = 110101101
print(base2_to_base8(binary_num)) # Output: 655
71 chars
3 lines

So the binary number 110101101 is converted to base 8 as 655.

gistlibby LogSnag