字符串转二进制

来源:互联网 发布:mac系统下gem安装sass 编辑:程序博客网 时间:2024/06/01 20:35

chr():

>>> help(chr)Help on built-in function chr in module builtins:chr(i, /)    Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

参数是0 - 256 的一个整数,返回值是当前整数对应的ascii字符。参数可以是10进制也可以是16进制的形式

十六进制:

>>> print(chr(0x30),chr(0x31),chr(0x61))0 1 a

十进制:

>>> print(chr(48),chr(49),chr(97))0 1 a

ord()

>>> help(ord)Help on built-in function ord in module builtins:ord(c, /)    Return the Unicode code point for a one-character string.
>>> print(ord('0'),ord('1'),ord('a'))48 49 97

字符串转二进制:

>>> string = 'hello world'>>> def encode(string):    encode_str = ' '.join([bin(ord(c)).replace('0b', '') for c in string])    return encode_str>>> def decode(string):    decode_str = ''.join(chr(i) for i in [int(b, 2) for b in string.split(' ')])    return decode_str>>> str1 = encode(string)>>> str2 = decode(str1)>>> print(str1 + '\n' + str2)1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100hello world>>> 
原创粉丝点击