pythonbinary

How do I create a space after every 4 bits in python in a binary conversion program


import collections
from collections import Counter
d = int(input('Pick a number to convert to Binary: '))

def convert(n, Counter = 0):
    Counter = 0
    if n > 1:
        convert(n//2)
    print(n % 2, end = '')
    
    
print("Your number in Binary is")
convert(d)

I have no idea how to create a space every 4 bits or every 4 numbers in the output. I tried using a counter a for loop and pretty much everything I can think of. I just want to know how I would be able to do this. Any help would be appreciated, i'm just lost.


Solution

  • Try doing this:

    def convert(n, counter = None):
        if not counter:
            counter = 0
        counter += 1
        if n > 1:
            convert(n//2, counter)
        if counter % 4 == 0:
            print(" ", end="")
        print(n % 2, end = '')
        
        
        
    print("Your number in Binary is")
    convert(d)
    print("")
    

    Output of 3456 as input:

    Your number in Binary is
     1101 1000 0000