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.
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)
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()
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!