Converting Binary to ASCII and Vice Versa
Python offers various methods to encode strings into their binary representation and vice versa.
String to Binary
The provided code uses reduce to convert a string to binary. However, a simpler way is using the binascii module in Python 2 and int.from_bytes in Python 3:
import binascii binary = bin(int(binascii.hexlify('hello'), 16)) # Python 2 binary = bin(int.from_bytes('hello'.encode(), 'big')) # Python 3+
Binary to String
To reverse the process, use the binascii.unhexlify in Python 2 and the int.to_bytes method in Python 3:
text = binascii.unhexlify('%x' % n) # Python 2 text = n.to_bytes((n.bit_length() + 7) // 8, 'big').decode() # Python 3+
UTF-8 Support
To support all Unicode characters in Python 3, you can create custom functions for conversion:
def text_to_bits(text, encoding='utf-8', errors='surrogatepass'): # Converts text to bits, supporting all Unicode characters ... def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'): # Converts bits back to text, supporting all Unicode characters ...
This custom function is compatible with both Python 2 and Python 3.
In summary, Python provides various methods for binary-string conversions. The above solutions offer efficient and flexible ways to handle this task, including support for Unicode characters.
The above is the detailed content of How Can I Efficiently Convert Between Binary and ASCII Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!