开发者

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

开发者 https://www.devze.com 2023-03-31 08:27 出处:网络
I have a binary string r开发者_开发问答epresentation of a byte, such as 01010101 How can I convert it to a real binary value and write it to a binary file?Use the int function with a base of 2 to r

I have a binary string r开发者_开发问答epresentation of a byte, such as

01010101

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


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

精彩评论

暂无评论...
验证码 换一张
取 消