Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

binary

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?

like image 885
xiaohan2012 Avatar asked Aug 27 '11 10:08

xiaohan2012


People also ask

How to convert an integer to a one-byte string in Python?

Python 2 uses strings to handle binary data, so you would use the chr () function to convert the integer to a one-byte string. 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.

How to convert string to binary in Python?

3. Map () to convert string to binary in Python In this example, we are using the bytearray that returns an array of the byte in our example its returns an array of bytes for a given string “str”, using map () along with bin () to get the binary of given string. 4. Math Module,ord (),bin () to convert string to binary

What are bytestrings in Python 3?

Bytestrings in Python 3 are officially called bytes, an immutable sequence of integers in the range 0 <= x < 256. Another bytes -like object added in 2.6 is the bytearray - similar to bytes, but mutable. Let's take a look at how we can convert bytes to a String, using the built-in decode () method for the bytes class:

What is a byte array in Python?

A byte array is a set of bytes that may store a list of binary data. Instead of iterating over the string explicitly, we can iterate over a byte sequence.


1 Answers

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)
like image 162
Jeremy Avatar answered Oct 02 '22 20:10

Jeremy