Converting Binary to ASCII and Back
The given code snippet converts a string into binary representation. To comprehend its mechanism, let's analyze an alternative approach.
Python 2: ASCII Character Range
For ASCII characters within the range [ -~], Python 2 provides a simpler solution:
import binascii n = int(binascii.hexlify('hello'), 16) binary_representation = bin(n)
This code converts the string 'hello' into a hexadecimal representation and then into a binary representation.
Reversing the Conversion
To convert the binary representation back to a string:
n = int('0b110100001100101011011000110110001101111', 2) string_representation = binascii.unhexlify('%x' % n)
This converts the binary representation back into a hexadecimal representation and then into the original string 'hello.'
Python 3.2 :
Python 3.2 introduced additional methods:
n = int.from_bytes('hello'.encode(), 'big') binary_representation = bin(n)
n = int('0b110100001100101011011000110110001101111', 2) string_representation = n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()
Unicode Support in Python 3:
To support all Unicode characters in Python 3:
def text_to_bits(text, encoding='utf-8', errors='surrogatepass'): # ... def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'): # ...
This function converts between text and binary representations, supporting Unicode characters.
The above is the detailed content of How to Convert Between ASCII and Binary Representations in Python?. For more information, please follow other related articles on the PHP Chinese website!