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 binascii module.

To convert ASCII to binary, we write:

import binascii

b = bin(int(binascii.hexlify(b'hello'), 16))
print(b)

We call binascii.hexlify with b'hello' to convert the binary string to hex.

Then we call int to convert the hex to a decimal integer.

And then we call bin to convert the int to a binary string.

Therefore, b is 0b110100001100101011011000110110001101111.

To convert binary to ASCII, we call binascii.unhexlify.

For instance, we write:

import binascii

n = int('0b110100001100101011011000110110001101111', 2)
s = binascii.unhexlify('%x' % n)
print(s)

We call int with a binary string and 2 as the base.

Then we call binascii.unhexlify with '%x' % n to convert the int to a binary string.

Therefore s is b'hello'.

Conclusion

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

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 *