Home > Backend Development > Python Tutorial > How to Efficiently Convert Between Binary and ASCII in Python?

How to Efficiently Convert Between Binary and ASCII in Python?

Barbara Streisand
Release: 2024-12-05 15:10:11
Original
956 people have browsed it

How to Efficiently Convert Between Binary and ASCII in Python?

Converting Between Binary and ASCII

The provided code converts a string to binary using a reduction lambda function. However, the method for converting binary back to ASCII is not immediately apparent.

Python 2 (For ASCII Characters)

For ASCII characters in the range [ -~], Python 2 offers an easy solution:

import binascii
bin(int(binascii.hexlify('hello'), 16))
# Output: '0b110100001100101011011000110110001101111'
Copy after login

To reverse the process:

n = int('0b110100001100101011011000110110001101111', 2)
binascii.unhexlify('%x' % n)
# Output: 'hello'
Copy after login

Python 3 (All Unicode Characters)

Python 3 introduced support for all Unicode characters. The following functions provide a unified conversion interface:

def text_to_bits(text):
    bits = bin(int.from_bytes(text.encode(), 'big'))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits):
    n = int(bits, 2)
    return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()
Copy after login

Unicode-Aware Conversion

Finally, for Python 2 and 3 compatibility, here's a single-source code snippet that handles Unicode conversion:

def text_to_bits(text):
    bits = bin(int(binascii.hexlify(text.encode()), 16))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits):
    n = int(bits, 2)
    return int2bytes(n).decode()

def int2bytes(i):
    hex_string = '%x' % i
    n = len(hex_string)
    return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
Copy after login

The above is the detailed content of How to Efficiently Convert Between Binary and ASCII in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template