問題描述
我有一個(gè)字節(jié)的二進(jìn)制字符串表示,比如
I have a binary string representation of a byte, such as
01010101
如何將其轉(zhuǎn)換為真正的二進(jìn)制值并將其寫入二進(jìn)制文件?
How can I convert it to a real binary value and write it to a binary file?
推薦答案
使用int
函數(shù) 使用 base
的 2
來讀取二進(jìn)制值作為整數(shù).
Use the int
function with a base
of 2
to read a binary value as an integer.
n = int('01010101', 2)
Python 2 使用字符串來處理二進(jìn)制數(shù)據(jù),因此您可以使用 chr()
函數(shù) 將整數(shù)轉(zhuǎn)換為單字節(jié)字符串.
Python 2 uses strings to handle binary data, so you would use the chr()
function to convert the integer to a one-byte string.
data = chr(n)
Python 3 處理二進(jìn)制和文本的方式不同,因此您需要使用 <代碼>字節(jié)類型代替.這沒有直接等效于 chr()
函數(shù),但 bytes
構(gòu)造函數(shù)可以采用字節(jié)值列表.我們將 n
放在一個(gè)元素?cái)?shù)組中,并將其轉(zhuǎn)換為 bytes
對象.
Python 3 handles binary and text differently, so you need to use the bytes
type instead. This doesn't have a direct equivalent to the chr()
function, but the bytes
constructor can take a list of byte values. We put n
in a one element array and convert that to a bytes
object.
data = bytes([n])
一旦你有了你的二進(jìn)制字符串,你就可以以二進(jìn)制模式打開一個(gè)文件并將數(shù)據(jù)寫入它,如下所示:
Once you have your binary string, you can open a file in binary mode and write the data to it like this:
with open('out.bin', 'wb') as f:
f.write(data)
這篇關(guān)于在 Python 中將字節(jié)的二進(jìn)制字符串表示形式轉(zhuǎn)換為實(shí)際的二進(jìn)制值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!