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

Recommended Answers

All 4 Replies

>>> print(chr(76), bin(76)[2:].zfill(8))
('L', '01001100')
commented: Nice call on the .zfill. Used it on my return line for binary and it worked perfectly. Thanks. +0

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.

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

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

I am using 2.7

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.