Python 16进制、字符串转换


# 把16进制字符 转化为对应固定长度为8的bit串
bits_str = '{:08b}'.format(ord(data))

# 把字符串 转化为对应的16进制串
def str_to_hex(s):
    return ' '.join([hex(ord(c)).replace('0x', '') for c in s])

# 把16进制串 转化为对应的字符串
def hex_to_str(s):
    return ''.join([chr(i) for i in [int(b, 16) for b in s.split(' ')]])

# 把字符串 转化为对应的bit串
def str_to_bin(s):
    return ' '.join([bin(ord(c)).replace('0b', '') for c in s])

# 把bit串 转化为对应的字符串
def bin_to_str(s):
    return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])