Home > Backend Development > Python Tutorial > How to Efficiently Convert Binary to ASCII and Vice Versa in Python?

How to Efficiently Convert Binary to ASCII and Vice Versa in Python?

Linda Hamilton
Release: 2024-11-28 10:06:13
Original
135 people have browsed it

How to Efficiently Convert Binary to ASCII and Vice Versa in Python?

Convert Binary to ASCII and Vice Versa

Converting between binary and ASCII is essential for encoding and decoding digital data. Here are methods to perform this conversion effectively in Python, addressing the challenges you mentioned:

Converting String to Binary

To convert a string to binary, you can use:

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

This converts the string to a hex representation and then to binary, producing the same output you obtained.

Converting Binary to String

For conversion from binary to string, utilize:

n = int('0b110100001100101011011000110110001101111', 2)
binascii.unhexlify('%x' % n)
Copy after login

This transforms the binary string to a hex value and then decodes it to the original string.

Python 3.2 Compatibility

In Python 3.2 and above, you can employ the following methods:

bin(int.from_bytes('hello'.encode(), 'big'))
n = int('0b110100001100101011011000110110001101111', 2)
n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()
Copy after login

These methods utilize the int.from_bytes() and int.to_bytes() functions, providing an efficient way to handle binary data.

Supporting Unicode Characters (Python 3)

To handle Unicode characters in Python 3, use:

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 &amp; 1)))
Copy after login
'

These functions encode and decode text with a specified encoding and error handling, ensuring the correct handling of Unicode characters.

Single-Source Python 2/3 Compatible Version

This code is compatible with both Python 2 and 3:

This code handles both Python versions while providing a consistent set of functions for binary and ASCII conversions.

The above is the detailed content of How to Efficiently Convert Binary to ASCII and Vice Versa 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