Here's an example of doing it the first way that Patrick mentioned: convert the bitstring to an int and take 8 bits at a time. The natural way to do that generates the bytes in reverse order. To get the bytes back into the proper order I use extended slice notation on the bytearray with a step of -1: b[::-1].

def bitstring_to_bytes(s):
    v = int(s, 2)
    b = bytearray()
    while v:
        b.append(v & 0xff)
        v >>= 8
    return bytes(b[::-1])

s = "0110100001101001"
print(bitstring_to_bytes(s))

Clearly, Patrick's second way is more compact. :)

However, there's a better way to do this in Python 3: use the int.to_bytes method:

def bitstring_to_bytes(s):
    return int(s, 2).to_bytes((len(s) + 7) // 8, byteorder='big')

If len(s) is guaranteed to be a multiple of 8, then the first arg of .to_bytes can be simplified:

return int(s, 2).to_bytes(len(s) // 8, byteorder='big')

This will raise OverflowError if len(s) is not a multiple of 8, which may be desirable in some circumstances.


Another option is to use double negation to perform ceiling division. For integers a & b, floor division using //

n = a // b

gives the integer n such that
n <= a/b < n + 1
Eg,
47 // 10 gives 4, and

-47 // 10 gives -5. So

-(-47 // 10) gives 5, effectively performing ceiling division.

Thus in bitstring_to_bytes we could do:

return int(s, 2).to_bytes(-(-len(s) // 8), byteorder='big')

However, not many people are familiar with this efficient & compact idiom, so it's generally considered to be less readable than

return int(s, 2).to_bytes((len(s) + 7) // 8, byteorder='big')
Answer from PM 2Ring on Stack Overflow
Top answer
1 of 3
31

Here's an example of doing it the first way that Patrick mentioned: convert the bitstring to an int and take 8 bits at a time. The natural way to do that generates the bytes in reverse order. To get the bytes back into the proper order I use extended slice notation on the bytearray with a step of -1: b[::-1].

def bitstring_to_bytes(s):
    v = int(s, 2)
    b = bytearray()
    while v:
        b.append(v & 0xff)
        v >>= 8
    return bytes(b[::-1])

s = "0110100001101001"
print(bitstring_to_bytes(s))

Clearly, Patrick's second way is more compact. :)

However, there's a better way to do this in Python 3: use the int.to_bytes method:

def bitstring_to_bytes(s):
    return int(s, 2).to_bytes((len(s) + 7) // 8, byteorder='big')

If len(s) is guaranteed to be a multiple of 8, then the first arg of .to_bytes can be simplified:

return int(s, 2).to_bytes(len(s) // 8, byteorder='big')

This will raise OverflowError if len(s) is not a multiple of 8, which may be desirable in some circumstances.


Another option is to use double negation to perform ceiling division. For integers a & b, floor division using //

n = a // b

gives the integer n such that
n <= a/b < n + 1
Eg,
47 // 10 gives 4, and

-47 // 10 gives -5. So

-(-47 // 10) gives 5, effectively performing ceiling division.

Thus in bitstring_to_bytes we could do:

return int(s, 2).to_bytes(-(-len(s) // 8), byteorder='big')

However, not many people are familiar with this efficient & compact idiom, so it's generally considered to be less readable than

return int(s, 2).to_bytes((len(s) + 7) // 8, byteorder='big')
2 of 3
11
>>> zero_one_string = "0110100001101001"
>>> int(zero_one_string, 2).to_bytes((len(zero_one_string) + 7) // 8, 'big')
b'hi'

It returns bytes object that is an immutable sequence of bytes. If you want to get a bytearray -- a mutable sequence of bytes -- then just call bytearray(b'hi').

๐ŸŒ
Python Guides
pythonguides.com โ€บ python-string-to-byte-array
Convert a String to a Byte Array in Python
September 23, 2025 - # Convert string to mutable byte array using bytearray() text = "Python is powerful!" byte_array = bytearray(text, 'utf-8') print("Original String:", text) print("Converted Byte Array:", byte_array) print("Type of Object:", type(byte_array)) # Modifying the byte array byte_array[0] = 80 # ASCII value for 'P' print("Modified Byte Array:", byte_array) You can refer to the screenshot below to see the output. The advantage of bytearray() is that you can modify the contents later. This is helpful when working with binary protocols where you need to update specific bytes. The third method I use frequently is the encode() method of Python strings.
Discussions

How to convert string to byte array in Python - Stack Overflow
Say that I have a 4 character string, and I want to convert this string into a byte array where each character in the string is translated into its hex equivalent. e.g. str = "ABCD" I'm trying to ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to convert string to byte arrays? - Stack Overflow
For those who are wondering why you would want to do this: I found this to be useful for parsing binary data read using pySerial. ... Save this answer. ... Show activity on this post. Python 2.6 and later have a bytearray type which may be what you're looking for. Unlike strings, it is mutable, ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to convert string to binary? - Stack Overflow
Otherwise, if you want them in form of zeros and ones --binary representation-- as a more pythonic way you can first convert your string to byte array then use bin function within map : More on stackoverflow.com
๐ŸŒ stackoverflow.com
How do I convert a string to bytes?
Or use the bytes() builtin function . An example: x = "abcโ˜บxyz" print(x) y = bytes(x, encoding="utf-8") print(y) More on reddit.com
๐ŸŒ r/learnpython
15
6
August 8, 2023
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-convert-string-to-bytes
Convert String to bytes-Python - GeeksforGeeks
Explanation: bytes() constructor converts a string to bytes using the specified encoding, here "utf-8", allowing the string to be processed as binary data.
Published: April 27, 2025
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ string to binary python
How to Convert a String to Binary in Python | Delft Stack
February 2, 2024 - We can also use the map() function in replacement of the format() function. map() convert string to a byte array using the bytearray() function and then use bin to convert the array of bytes in binary representation.
๐ŸŒ
Theunterminatedstring
theunterminatedstring.com โ€บ python-bits-and-bytes
Python Bits and Bytes - The Unterminated String
May 19, 2018 - The key functions in this module are struct.pack() and struct.unpack(). In addition to the data, these functions require a format string to be provided to specify the byte order and the intended binary layout of the data.
๐ŸŒ
CodingTechRoom
codingtechroom.com โ€บ question โ€บ convert-binary-string-to-byte-array
How to Convert a Binary String to a Byte Array in Programming - CodingTechRoom
Converting a binary string to a byte array is a common task in many programming languages. This conversion allows for manipulation of binary data in a more usable format, such as for file handling, network communications, and more. Below, we will discuss the methods to achieve this conversion in different programming languages. ... # Python example of converting a binary string to a byte array binary_string = '10101000' byte_array = int(binary_string, 2).to_bytes((len(binary_string) + 7) // 8, byteorder='big') print(list(byte_array)) # Output: [168]
Find elsewhere
๐ŸŒ
Pierian Training
pieriantraining.com โ€บ home โ€บ how to convert a string to bytes using python
Understanding String and Bytes Conversions in Python
April 27, 2023 - Then we create another variable named b, which stores the bytes representation of our initial string by passing it as the first argument to bytearray(), followed by specifying the encoding format (in this case 'utf-8'). The resulting byte array ...
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ representing-binary-data-with-bytes
Representing binary data with bytes - Python Morsels
August 3, 2026 - The decode method (without any arguments passed to it) uses a default character encoding of utf-8. Even if we know that the data we're working with uses that default character encoding of utf-8, it's considered a best practice to always specify the encoding of our bytes: >>> text = data.decode("utf-8") >>> text 'bytes! โœจ' As the Zen of Python says, "explicit is always better than implicit". If for some reason you have a string you want to turn into bytes, you can call the encode method on that string to encode it into bytes:
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ string-to-bytes-conversion
How to Convert String to Bytes in Python | DataCamp
June 5, 2024 - In Python, use the .encode() method on a string to convert it into bytes, optionally specifying the desired encoding (UTF-8 by default).
๐ŸŒ
Chilkat
chilkatsoft.com โ€บ python_binary_string_vs_byte_array.asp
Python Binary Strings vs Byte Arrays
binary_string[0] = 255 # TypeError: 'bytes' object does not support item assignment ยท Solution: If you need to modify it, convert to "bytearray". A "bytearray" is similar to "bytes", but modifiable. byte_arr = bytearray([0, 1, 2, 3, 4]) print(byte_arr) # Output: bytearray(b'\x00\x01\x02\x03\x04')
๐ŸŒ
Real Python
realpython.com โ€บ python-bytes
Bytes Objects: Handling Binary Data in Python โ€“ Real Python
March 5, 2025 - Here are some examples: Knowing these details allows you to implement the following helper functions for constructing such messages in Python: ... def array(*items): binary = bytearray...
Top answer
1 of 10
174

Something like this?

>>> st = "hello world"
>>> ' '.join(format(ord(x), 'b') for x in st)
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

#using `bytearray`
>>> ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'
2 of 10
133

If by binary you mean bytes type, you can just use encode method of the string object that encodes your string as a bytes object using the passed encoding type. You just need to make sure you pass a proper encoding to encode function.

In [9]: "hello world".encode('ascii')                                                                                                                                                                       
Out[9]: b'hello world'

In [10]: byte_obj = "hello world".encode('ascii')                                                                                                                                                           

In [11]: byte_obj                                                                                                                                                                                           
Out[11]: b'hello world'

In [12]: byte_obj[0]                                                                                                                                                                                        
Out[12]: 104

Otherwise, if you want them in form of zeros and ones --binary representation-- as a more pythonic way you can first convert your string to byte array then use bin function within map :

>>> st = "hello world"
>>> map(bin,bytearray(st))
['0b1101000', '0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111', '0b1101111', '0b1110010', '0b1101100', '0b1100100']
 

Or you can join it:

>>> ' '.join(map(bin,bytearray(st)))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'

Note that in python3 you need to specify an encoding for bytearray function :

>>> ' '.join(map(bin,bytearray(st,'utf8')))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'

You can also use binascii module in python 2:

>>> import binascii
>>> bin(int(binascii.hexlify(st),16))
'0b110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'

hexlify return the hexadecimal representation of the binary data then you can convert to int by specifying 16 as its base then convert it to binary with bin.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how do i convert a string to bytes?
r/learnpython on Reddit: How do I convert a string to bytes?
August 8, 2023 -

Suppose I something like

s = "GW\x25\001"

How do I convert that string to bytes, interpreting the backslashes as escapes? In other words, the resulting byte array should be of length 4.

UPDATE: Hmmm, I was taking the string from sys.argv[1], which seems to complicate things and not make it turn out as expected. So I'm still not sure what the answer is.

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 66326599 โ€บ faster-way-to-convert-large-byte-string-to-array-of-binary-strings-in-python
Faster way to convert large byte string to array of binary strings in Python - Stack Overflow
February 23, 2021 - Oh and I should mention that I've tried several other approaches like using map(np.binary_repr,ints) but so far everything else I've tried was slower than the function above. ... Instead of squeezing a tiny bit of performance out of the conversion from integer to string it would be far more efficient to just drop the conversion entirely and operate on the integer's bits directly instead of operating on characters in a string representing that integer.
๐ŸŒ
Jeremy Morgan
jeremymorgan.com โ€บ python โ€บ how-to-convert-string-to-bytes-in-python
How to Convert String to Bytes in Python - Jeremy Morgan's
December 8, 2023 - Another way to convert a string into bytes is by using the bytearray() function. This function takes a string as an argument and returns a byte array that represents the encoded string.
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ built-in โ€บ bytearray()
Python bytearray() - Create Byte Array
September 27, 2024 - example_string = "Hello, world!" byte_array = bytearray(example_string, encoding='utf-8') print(byte_array) ... This code snippet creates a bytearray from a string, using UTF-8 encoding. The print statement will show the bytearray representation of "Hello, world!". Generate a bytearray from ...