pu369com

python bytes格式的一些转换

import binascii

#中文字符串转bytes
s = "中国"
b = s.encode("utf-8")
print(b)  #输出:b'\xe4\xb8\xad\xe5\x9b\xbd'

#bytes转字符串,默认utf-8解码
print(b.decode()) #输出:中国

#16进制字符串转bytes
hex_s = "e4b8ade59bbd"
b = bytes.fromhex(hex_s)
print(b) #输出:b'\xe4\xb8\xad\xe5\x9b\xbd'

#英文bytes转16进制bytes
b = b"China" #这里不能用中文
hex_s = binascii.hexlify(b)
print(hex_s)  #输出:b'4368696e61'
#再转为字符串
print(hex_s.decode()) #输出:4368696e61

def byte_to_binary(byte):
    return ''.join(f'{i:08b}' for i in byte)

def bytes_to_binary(data):
    return ''.join([bin(byte)[2:].zfill(8) for byte in data])

#byte转2进制 
bytes_data = b'\xe4\xb8\xad\xe5\x9b\xbd'
binary_str = bytes_to_binary(bytes_data)
print(binary_str)  #输出:111001001011100010101101111001011001101110111101
 

 

posted on 2024-03-15 13:27  pu369com  阅读(71)  评论(0编辑  收藏  举报

导航