So, I found a snipped of code that did what I was looking for but I tried adding upon it to fit my need a little more. What I am trying to do is input an integer and return an 8 bit binary string to a list.

My first problem is that if the last digit is 0 with no remainder it stops the binary string.

Second I need this to a list instead of a string.

def binary(user, digits=8):
    binary = ''
    while user != 0 and digits <=8:
        if user % 2 == 0: bit = '0'
        else: bit = '1'
        binary = bit + binary
        user >>= 1
    return binary or '0'



while True:
    try:
        user = int(raw_input("Enter an integer between 0 and 255: "))
        n = str(user)
        if user <= 255:
            while user in range(0,256):
                print "ASCII:  ",chr(user)
                print "Binary: ", binary(user)
            
                break
            
    except ValueError:
        print "Please enter a valid integer."

For example my binary string result if my integer was 76 would be 1001100 ... I really need that last zero.... 01001100

Edited 5 Years Ago by gork000: n/a

>>> print(chr(76), bin(76)[2:].zfill(8))
('L', '01001100')

Edited 5 Years Ago by pyTony: n/a

Comments
Nice call on the .zfill. Used it on my return line for binary and it worked perfectly. Thanks.

Unfortunately I can not use bin or hex as this is for an assignment and I have to do it the long way. I should of mentioned that because that is the obvious way.

Edited 5 Years Ago by gork000: n/a

OK. I was going to suggest bin() but apparently we cross posted.

Edited 5 Years Ago by griswolf: n/a

What version of Python are you using? Mine has a builtin function bin(integer) that returns a binary string...

I am using 2.7

This question has already been answered. Start a new discussion instead.