Given a number in base 2 convert it into base 6 Python

This post deals with the methods to inter-convert decimal to any base system number into any base depending on the user input in Python.

Prerequisites: Basics of python looping constructs

Decimal to Any Base – The Method

The basic algorithm for this conversion is to repeatedly divide (integer division) the given decimal number by the target base value until the decimal number becomes 0. The remainder in each case forms the digits of the number in the new base system, however, in the reverse order.

An Upper Limit

The algorithm, in general, will work for any base, but we need digits/characters to represent that many numbers of a base system. For simplicity, we limit ourselves to base 36 i.e 10 numbers + 26 alphabets. (We can differentiate lower and upper case, but we intend to focus on the algorithm here!). It will be clear after the implementation that the method has to work for any base.

Decimal to Any Base – Python Implementation

Consider the following program,

def dec_to_base(num,base):  #Maximum base - 36
    base_num = ""
    while num>0:
        dig = int(num%base)
        if dig<10:
            base_num += str(dig)
        else:
            base_num += chr(ord('A')+dig-10)  #Using uppercase letters
        num //= base

    base_num = base_num[::-1]  #To reverse the string
    return base_num

Notice the if condition used to check if digits 0-9 are enough to accommodate all digits in the base. Otherwise, we are assigning a suitable alphabet for the digit.

ord() – Built-in function that returns the ASCII value of character

chr() – Built-in function that returns the character with ASCII value –

The last line is used as a string reversal operation. It basically produces a slice of string from beginning to end ( signified by first two empty arguments) by traversing from the end to start (signified by -1).

This a sample output, converting to base 28

Given a number in base 2 convert it into base 6 Python
Given a number in base 2 convert it into base 6 Python

Hence we are able to convert a decimal number into any base required.

Some Built-In Base Conversion Methods

Python provides some built-in base conversion methods for binary, octal and hexadecimal numbers.

The usage is very simple:

bin() – Returns a string, which is binary representation of decimal number

oct() – Returns a string, which is octal representation of decimal number

hex() – Returns a string, which is hecadecimal representation of decimal number

Any Base to Decimal

Python also provides easy conversion from any base to decimal. This done by simply passing a string that has the other base representation of a decimal number and the base value as the second argument. It returns the decimal number!

print int("1123",5)   #Prints string given in base-5 in decimal

The output is: 163

Algorithm and Implementation for Any Base to Decimal

The logic is very simple. We just have to multiply each digit at a position with the base value raised to the place value(starting from 0 from right-side). That is how a base system is defined, in fact.

For instance, if 1011 is a binary number, the decimal equivalent is

(1 x 2^0) + (1 x 2^1) + (0 x 2^2) + (1 x 2^3) = 11

The following program illustrates the same,

def base_to_dec(num_str,base):
    num_str = num_str[::-1]
    num = 0
    for k in range(len(num_str)):
        dig = num_str[k]
        if dig.isdigit():
            dig = int(dig)
        else:    #Assuming its either number or alphabet only
            dig = ord(dig.upper())-ord('A')+10
        num += dig*(base**k)
    return num

Below is a sample output for the same value converted in the previous output

Given a number in base 2 convert it into base 6 Python
Given a number in base 2 convert it into base 6 Python

Feel free to leave behind any sort of feedback, suggestion, doubts below.

6 responses to “Inter-Convert Decimal and Any Base Using Python”

  1. Miss TJ Mawela says:

    Why does the code immediately break when I run it?

    • Karthik Desingu says:

      Please note that the posted programs are in Python 2.7.x
      Secondly, the code is only a function definition and the function call needs to be added

      If this is not the issue, do mention which of the two codes (decimal to other base or vice-versa) you are referring to and what error is being raised

  2. hint says:

    You advertise as “Any Base” but your alphabet is only hexadecimal.

  3. Karthik Desingu says:

    This post describes a general algorithm to allow interconversions between any base and base 10.

    Even the sample output attached with this post demonstrates a conversion between base 28 and decimal. It is not true that the program is limited only to hexadecimal.

    However, as mentioned under the “An Upper Limit” section of the post, for the sake of simplicity, only alphabets and numbers are being used to represent digits of the base. So with this particular implementation of the algorithm, all bases from 2 to 36 can be interconverted with base 10 (which is also clearly mentioned in the post)

  4. John says:

    Write a class named ‘CarSpeed’ to calculate the speed (in miles/hour) of different brands of cars based on the information given in the table below. The formula to calculate speed is also given below. Based on your output, which brand of car has the highest speed?

    How do you convert base 2 to base 6 in Python?

    # Function To convert a decimal number into its equivalent number in base 6..
    def decToBase6(dec):.
    pv = 1..
    output = 0 # Output variable will store the base6 equivalent of the given binary number..
    # The while loop terminates when the dec number becomes equal to zero..
    while(dec > 0):.

    How do you convert a number to base 6?

    For example, to convert 83.125 to base 6 , we multiply the fractional part by 6 repeatedly until we find an integer..
    0.125 × 6 = 0 .75..
    0.75 × 6 = 4 .5..
    0.5 × 6 = 3..

    How do you convert a number to a different base in Python?

    In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in the case of binary numbers.

    How do you convert base 2 to other bases?

    Step 1 − Divide the decimal number to be converted by the value of the new base. Step 2 − Get the remainder from Step 1 as the rightmost digit (least significant digit) of new base number. Step 3 − Divide the quotient of the previous divide by the new base.