Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
862 views
in Technique[技术] by (71.8m points)

Convert binary string representation of a byte to actual binary value in Python

I have a binary string representation of a byte, such as

01010101

How can I convert it to a real binary value and write it to a binary file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the int function with a base of 2 to read a binary value as an integer.

n = int('01010101', 2)

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

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...