問題描述
我制作了一個小 Python 程序,它從文件中讀取二進制文件并將其存儲到文本文件中,讀取文本文件并存儲二進制文件.但是,我無法讓二進制文件工作......它像這樣讀取文件:
I've made a little python program that reads binary from a file and stores it to a text file, read the text file and store the binary. But, I can't get the binary to work... it reads the files like this:
f_bin = open(bin_file,"rb")
to_bin_data = f_bin.read()
bin_data = bin(reduce(lambda x, y: 256*x+y, (ord(c) for c in to_bin_data), 0))
f_bin.close()
這個對我不起作用... 將二進制轉換為ASCII,反之亦然
類似這個網頁:http://www.roubaixinteractive.com/PlayGround/Binary_Conversion/Binary_To_Text.asp
我現在為它制作了一個很長的 if else 腳本,但感謝您的回答
推薦答案
我們來看看'hello'這個詞,它是0110100001100101011011000110110001101111
Let's take the word 'hello' which is 0110100001100101011011000110110001101111
要將其轉換回字符,我們可以使用 chr
和 int
(以 2 為基數)以及一些列表切片...
To translate that back to characters we can use chr
and int
(with a base of 2) and some list slicing...
''.join(chr(int(bin_text[i:i+8], 2)) for i in xrange(0, len(bin_text), 8))
如果我們想將 'hello' 轉換為二進制,我們可以使用 ord
和字符串格式化...
If we wanted to take 'hello' and convert it to binary we can use ord
and string formatting...
''.join('{:08b}'.format(ord(c)) for c in 'hello')
這篇關于如何在python中將二進制字符串轉換為ascii字符串?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!