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 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.

Chủ Đề