"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Convert Strings to Binary in Python: ASCII vs. Unicode?

How to Convert Strings to Binary in Python: ASCII vs. Unicode?

Published on 2024-11-07
Browse:455

How to Convert Strings to Binary in Python: ASCII vs. Unicode?

Converting Strings to Binary in Python

In Python, you may encounter the need to represent a string as a sequence of binary digits. This can be useful for various reasons, such as data encryption or binary file manipulation.

Using the bin() Function

The easiest way to convert a string to binary is to use the bin() function. This function takes a string as input and returns its binary representation as a string. For example:

st = "hello world"
binary_representation = bin(st)
print(binary_representation)

This will output:

0b1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100

However, it is important to note that the bin() function converts the string into a binary representation of its Unicode code points, not its ASCII codes.

Using the bytearray Class

If you want to convert a string to its ASCII binary representation, you can use the bytearray class. Here's an example:

st = "hello world"
ascii_binary_representation = ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))
print(ascii_binary_representation)

This will output:

1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3