0

I need some help converting a string to binary. I have to do it using my own code, not built in functions (except I can use 'ord' to get the characters into decimal).

The problem I have is that it only seems to convert the first character into binary, not all of the characters of the string. For instance, if you type "hello" it will convert the h to binary but not the whole thing.

Here's what I have so far

def convertFile():

myList = []
myList2 = []
flag = True

string = input("input a string: ")

for x in string:
    x = ord(x)

    myList.append(x)
print(myList)

for i in range(len(myList)):
    for x in myList:
        print(x)

        quotient = x / 2
        quotient = int(quotient)
        print(quotient)
        remainder = x % 2
        remainder = int(remainder)
        print(remainder)
        myList2.append(remainder)
        print(myList2)

        if int(quotient) < 1:
            pass

        else:
            x = quotient

myList2.reverse()

print ("" .join(map(str, myList2)))

convertFile()
5
  • 1
    you need to write some function decToBin , or chrToBin, and call it for each letter ... Commented Mar 31, 2014 at 22:46
  • Perhaps binascii.hexlify or binascii.unhexlify? Commented Mar 31, 2014 at 22:53
  • What is your Python version? Commented Mar 31, 2014 at 22:56
  • related: Convert Binary to ASCII and vice versa (Python) Commented Mar 31, 2014 at 23:01
  • I am using version 3.3 Commented Apr 1, 2014 at 0:00

2 Answers 2

1

If you're just wanting "hex strings", you can use the following snippet:

''.join( '%x' % ord(i) for i in input_string )

Eg. 'hello' => '68656c6c6f', where 'h' => '68' in the ascii table.

Sign up to request clarification or add additional context in comments.

Comments

0
def dec2bin(decimal_value):
    return magic_that_converts_a_decimal_to_binary(decimal_value)

ordinal_generator =  (ord(letter) for letter in my_word) #generators are lazily evaluated
bins = [dec2bin(ordinal_value) for ordinal_value in ordinal_generator]
print bins

as an aside this is bad

for x in myList:
    ...
    x = whatever

since once it goes to x again at the top whatever you set x equal to gets tossed out and x gets assigned the next value in the list

1 Comment

You might mean: ''.join([dec2bin(ord(c), padding) for c in input_string]). Though ord(b'\xff') == 255 is not ascii. And ord('\N{snowman}') == 9731 is not ascii (if OP uses Python 3 as hinted by input() function)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.