Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

binary

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.

like image 525
Sielko Avatar asked Oct 18 '25 19:10

Sielko


1 Answers

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
like image 81
Pedro Maia Avatar answered Oct 22 '25 05:10

Pedro Maia