user3483014
user3483014

Reputation: 1

Converting a string to binary

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()

Upvotes: 0

Views: 298

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113950

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

Upvotes: 0

Travis D.
Travis D.

Reputation: 342

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.

Upvotes: 1

Related Questions