-1

I know that in python there are certain functions like bin that turn decimal numbers into binary numbers. I would like to build one myself. I have tried the following:

def binary(n):
    bina = ''
    B = []
    if n == 0:
        bina = '0'
    else: 
        while n>0:
            x = 0
            while 2**x<n:
                x = x+1
                B.append(x-1)
                n = n-2**(x-1)

The problem is that when I have the exponents with base 2 in the array B I don’t know how to actually read them so that I obtain the actual binary number made of ones and zeroes. How can I make the code above work?

before someone says that my question was already asked, my question is how can I make the code above work,I know that there are other methods to make a binary convertion in python, but I would like to know what's wrong with mine and possibly make my code work.

Emilio
  • 102
  • 11

1 Answers1

0
def make_binary(num):
    binary = ''
    while num > 0:
        binary = str(num % 2) + binary
        num = num // 2
    return binary
print(make_binary(15))
Parvesh Kumar
  • 1,104
  • 7
  • 16
  • It can also be done using bit shift and bitwise comparison: `binary = str(num & 1) + binary` and `num = num >> 1` – Jenny Feb 16 '22 at 14:03