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

How to Convert Between ASCII and Binary Representations in Python?

Patricia Arquette
Release: 2024-11-30 14:52:10
Original
219 people have browsed it

How to Convert Between ASCII and Binary Representations in Python?

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)
Copy after login

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)
Copy after login

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)
Copy after login
n = int('0b110100001100101011011000110110001101111', 2)
string_representation = n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()
Copy after login

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'):
    # ...
Copy after login

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!

source:php.cn
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