Convert number to binary

Asked

Viewed 601 times

0

I’m having trouble with the logic of my code:

dec = (10)
dup = dec
co = 2
exp = 0
res = (tuple)
while True:
    dup = dec
    dec = int(dec / co)
    exp += dup * co
    print(f'dec {dec} dup {dup} exp {exp}')
    if exp - dup == 0:
        res += 0
    elif exp - dup == 1:
        res += 1
    elif dec / co == 0:
        res += 0
        break
print(res)

I tried to make a translator of decimal numbers to binaries in a mathematical way, it just returns me 0 and the tuple does not accumulate the values.

  • This code does not return 0, actually it gives error: https://ideone.com/jNJuM0 - and is very confused, with variable names that do not help, besides res = (tuple) make no sense (the variable receives the class tuple, and not a tuple). Not to mention tuples are immutable and not the right type for something that will have things added dynamically

1 answer

1

The code is very confusing and I really could not understand how it tries to convert a number to base 2. A factor that contributes to this is the names of the variables, very confusing and that do not explain what they serve each one. It may seem like a minor detail, but give better names helps you program and understand what the code does.

And as already said in the comments, this code does not return zero, in fact it error when executing. One of the reasons is the line res = (tuple), that doesn’t make sense. You’re attributing the class tuple to the variable (which is different from creating a tuple containing some values).

Anyway, one way to solve this mathematically (with caveats, read more about it below) is:

# "converte" n para uma outra base
def converter(n, base):
    if base == 10: # se for base 10, retorna o próprio número
        return n

    result = expoente = 0
    while n > 0:
        n, digito = divmod(n, base)
        result += (10 ** expoente) * digito
        expoente += 1

    return result

print(converter(21, 2)) # 10101

I used divmod, which returns the result of the division and the rest of this division (i.e., at each iteration n is updated by the result of the split by base, and the digito is the rest of this same division). With that I already update the value of n and take the corresponding digit that will be used.

Then I add the digit to the result (I use an exponent because in the first iteration I have the last digit, in the second iteration I have the penultimate, etc, so the exponent is to ensure that the digit will be in the correct position).

In the example above the number has been returned 10101. Remember that this is the number "ten thousand one hundred and one". What I actually did was generate a number on base 10, whose digits correspond to 21 on base 2. But his value is ten thousand one hundred and one, so it’s no use using him thinking his value will be 21.


Another detail is that the function only works until base 10, since larger bases that require other symbols to represent the digits and for that would need to generate a string instead of a number. I mean, something like that:

def converter(n, base, simbolos):
    if base < 0 or base > len(simbolos):
        raise ValueError('base inválida')
    result = []
    while n > 0:
        result.insert(0, simbolos[n % base])
        n //= base
    return ''.join(result)

simbolos = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(converter(27, 2, simbolos)) # 11011
print(converter(27, 16, simbolos)) # 1B

Since now the return is a string, I can use letters, as in the case of 1B, representing 27 at base 16.

Browser other questions tagged

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