Categories
Python Answers

How to convert binary to ASCII and vice versa with Python?

Spread the love

Sometimes, we want to convert binary to ASCII and vice versa with Python.

In this article, we’ll look at how to convert binary to ASCII and vice versa with Python.

How to convert binary to ASCII and vice versa with Python?

To convert binary to ASCII and vice versa with Python, we can use the bin function to convert ASCII to binary.

For instance, we write

b = bin(int.from_bytes('hello'.encode(), 'big'))

to call int.from_bytes with the 'hello' string to create an int from the string.

Then we call bin to convert the int to bytes.

To convert binary to ASCII, we call to_bytes.

For instance, we write

n = int('0b110100001100101011011000110110001101111', 2)
s = n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()

to convert the binary string to an int.

Then we call to_bytes with the bit_length with (n.bit_length() + 7) // 8 and 'big' to convert the int to bytes.

And then we call decode to bytes back to a string.

Conclusion

To convert binary to ASCII and vice versa with Python, we can use the bin function to convert ASCII to binary.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *