-1

I am working on a code that converts from Binary to Decimal to Hexadecimal. I have completed the code and it functions properly; however, I would like to know how I seperate nibbles with spaces. Currently, I have it all functioning, but it only works with binary numbers written as 11111111 not 1111 1111. Does anyone know how I can accommplish this?

user_input = int(input("Enter a binary value: "))
nBits = list(str(user_input))

Steven Ka
  • 9
  • 3

2 Answers2

0

What you need to to remove the space in the string. You can do this by using the .replace function in python.

def Binary(Bits):
    n = 0 
    Counter = 0
    for i in reversed(Bits):
        n += 2**Counter * int(i)
        Counter+=1
    return n 

def main():
   
    while True: 
        user_input = int(input("Enter a binary value: "))
        nBits = list(str(user_input.replace(" ", "")))
        decimal = Binary(nBits)
        print("The decimal is:", decimal)
        
        Hexadecimal = ''
        Dict = {1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}

        while(decimal!=0):
            C = decimal%16 
            Hexadecimal =  Dict[C] + Hexadecimal 
            decimal = int(decimal/16)     
        print(Hexadecimal.replace(" ", ""))

main()

Varun W.
  • 242
  • 2
  • 14
0

edit: I have changed it, my apologies, strip only removes leading and trailing white space. use replace instead.

A simple replace on your input should work. Doing it like this ensures that you can type it either 11111111 or 1111 1111 and get the same result.

user_input = int(input("Enter a binary value: ").replace(' ', ''))