Home >Backend Development >Python Tutorial >How Can I Efficiently Convert Between Binary and ASCII (Including Unicode) in Python?

How Can I Efficiently Convert Between Binary and ASCII (Including Unicode) in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-26 05:35:11491browse

How Can I Efficiently Convert Between Binary and ASCII (Including Unicode) in Python?

Converting Binary to ASCII and Vice Versa

In Python, converting a string to its binary representation is straightforward. Using a combination of reduce(), lambda, ord(), and bin(), the binary equivalent of a string can be obtained. However, this approach requires manual string splicing and mapping to the corresponding ASCII values.

Simpler Conversion Methods

For Python 2, a more concise method is available using the binascii module:

import binascii
bin(int(binascii.hexlify('hello'), 16))

This method converts the ASCII characters in the range [-~, similar to the original code. For conversion back to a string:

binascii.unhexlify('%x' % n)

Python 3.2 Enhancements

In Python 3.2 and above, the bytes type offers additional convenience:

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

For conversion back to a string:

n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()

Unicode Support in Python 3

To support all Unicode characters in Python 3, the following function can be used:

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

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
    n = int(bits, 2)
    return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '<pre class="brush:php;toolbar:false">import binascii

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

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
    n = int(bits, 2)
    return int2bytes(n).decode(encoding, errors)

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

For Python 2/3 compatibility:

With these functions, converting between binary and Unicode strings becomes effortless in both Python 2 and Python 3.

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

Statement:
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