Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ASCII text string to binary string and vise versa (Python2/3 compatible)
# -*- coding: utf-8 -*-
'''
How to use binascii
1. ASCII text string to hex string
hex_string = binascii.hexlify(<ASCII_TEXT>.encode('utf-8'))
Hex string to ASCII text string
1. (python2,3)
ascii_text = binascii.unhexlify(<HEX_STRING>).decode('utf-8')
2. (python3)
n = int(<HEX_STRING>, 16)
ascii_text = n.to_bytes((n.bit_length() + 7) // 8, 'big').decode('utf-8')
3. (python3)
ascii_text = bytearray.fromhex(<HEX_STRING>).decode('utf-8')
4. (python2)
ascii_text = <HEX_STRING>.decode('hex')
'''
import sys
if sys.version_info[0] >= 3:
def ascii_to_bits(s, encoding='utf-8', errors='surrogatepass'):
"""ASCII text string to binary string."""
bits = bin(int.from_bytes(s.encode(encoding, errors), 'big'))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))
def bits_to_ascii(s, encoding='utf-8', errors='surrogatepass'):
"""Binary string to ASCII text string."""
n = int(s, 2)
return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '\x00'
else:
import binascii
def ascii_to_bits(s, encoding='utf-8', errors='surrogatepass'):
"""ASCII text string to binary string."""
bits = bin(int(binascii.hexlify(s.encode(encoding, errors)), 16))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))
def bits_to_ascii(s, encoding='utf-8', errors='surrogatepass'):
"""Binary string to ASCII text string."""
n = int(s, 2)
return _int_to_bytes(n).decode(encoding, errors)
def _int_to_bytes(s, i):
hex_string = hex(i)
n = len(hex_string)
return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.