我需要一些幫助將字符串轉換爲二進制。我必須使用自己的代碼來完成它,而不是內置函數(除非我可以使用'ord'來將字符轉換爲十進制)。將字符串轉換爲二進制
我的問題是,它似乎只是將第一個字符轉換爲二進制,而不是字符串的所有字符。例如,如果您輸入「hello」,它會將h轉換爲二進制文件,但不是整個文件。
這裏是我到目前爲止
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()
你需要寫一些函數'decToBin',或'chrToBin',併爲每個字母調用它... –
也許'binascii.hexlify'或'binascii.unhexlify'? –
你的Python版本是什麼? – jfs