Home > Software design >  Conversion of denary number to binary number problem (Python)
Conversion of denary number to binary number problem (Python)

Time:02-02

Im stuck on a problem where I have to write a function that converts a denary number into a binary number using the repeated division by two algorithm. Steps Include:

  • The number to be converted is divided by two.
  • The remainder from the division is the next binary digit. Digits are added to the front of the sequence.
  • The result is truncated so that the input to the next division by two is always an integer.
  • The algorithm continues until the result is 0.

Please click the link below to see what the output should be like: https://i.stack.imgur.com/pifUO.png

def dentobi(user):
  denary = user
  divide = user / 2
  remainder = user % 2
  binary = remainder
  
  if user != 0:
    print("Denary:", denary)
    print("Divide by 2:", divide)
    print("Remainder:", remainder)
    print("Binary:", binary)
  
user = int(input("Please enter a number: "))
dentobi(user)

This is what I have done so far but Im not getting anywhere.

Can someone explain how I would do this?

CodePudding user response:

One way, using divmod to divide by 2 and get the remainder in one step:

def binary(num):
    b = ""
    while num:
        num, digit = divmod(num, 2)
        b = f"{digit}{b}"
    return b

binary(26)
'11010'

This assumes a positive number but can easily be extended to work for 0 and negatives.

CodePudding user response:

The Answer provided by @user2390182 is functionally correct except that it returns an empty string when num is zero. However, I have noted on several occasions that divmod() is rather slow. This function is more complex but is faster:

def binary(n):
    r = []
    while n > 0:
        r.append('1' if n & 1 else '0')
        n //= 2
    return '0' if len(r) == 0 else ''.join(r[::-1])
  •  Tags:  
  • Related