Python-将二进制转换为ASCII,反之亦然

Python-将二进制转换为ASCII,反之亦然,第1张

Python-将二进制转换为ASCII,反之亦然

对于[ -~]Python 2 范围内的ASCII字符

>>> import binascii>>> bin(int(binascii.hexlify('hello'), 16))'0b110100001100101011011000110110001101111'

相反:

>>> n = int('0b110100001100101011011000110110001101111', 2)>>> binascii.unhexlify('%x' % n)'hello'

在Python 3.2+中:

>>> bin(int.from_bytes('hello'.enpre(), 'big'))'0b110100001100101011011000110110001101111'

相反:

>>> n = int('0b110100001100101011011000110110001101111', 2)>>> n.to_bytes((n.bit_length() + 7) // 8, 'big').depre()'hello'

要在Python中支持所有Unipre字符3:

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):    bits = bin(int.from_bytes(text.enpre(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').depre(encoding, errors) or ''

这是与Python 2/3兼容的单源版本:

import binasciidef text_to_bits(text, encoding='utf-8', errors='surrogatepass'):    bits = bin(int(binascii.hexlify(text.enpre(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).depre(encoding, errors)def int2bytes(i):    hex_string = '%x' % i    n = len(hex_string)    return binascii.unhexlify(hex_string.zfill(n + (n & 1)))

>>> text_to_bits('hello')'0110100001100101011011000110110001101111'>>> text_from_bits('110100001100101011011000110110001101111') == u'hello'True


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5431871.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存