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 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
标签:binary,输出,python,hex,bytes,print,格式,data From: https://www.cnblogs.com/pu369/p/18075208