Converting Bases to Python

Asked

Viewed 2,830 times

0

The code below takes a decimal number and converts to bases from 2 to 9

def converte(numDecimal, base):
    if numDecimal != 0:
        numConvertido = ""
        while numDecimal > 0:
            resto = numDecimal % base
            numConvertido = str(resto) + numConvertido
            numDecimal = numDecimal // base
    else:
        numConvertido = "0"
    return numConvertido


n = int(input())
while n != -1:
    for b in range(2, 9 + 1):
        r = converte(n, b)
        print(r, end=" ")
    print()
n = int(input())

If now I want to do the opposite, and receive a binary number and convert to bases from 3 to 10, for example, as I would?

  • The simplest is to interpret the binary as decimal and then use the function you already have of convesion to other bases

1 answer

1


Oops, greetings! Dude there is an easier way to convert numbers on different bases to integers on decimal basis, I’ll give you an example below: Below is a conversion of a binary number(String) to the decimal basis:

b = '0111'
print(int(b, 2))
>> 7

int() in this case takes two parameters, the first being the number to be converted that must be passed as string, and the second the base it is on, so we can do another example where a number is at base 5 and we want to convert it to decimal:

b = '0410'
print(int(b, 5))
>> 105

Knowing this, I think it makes it much easier to build your code! Now being direct to your question, when receiving a binary number and want to pass it to other bases, it would be better to convert it to decimal and then to the base in question using the function you already have.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.