字典与字节流的互转
1. hex stream(str) -> bytes
hex_stream_str ="hex stream str"
bytes = bytes.fromhex(hex_stream_str)
2. bytes -> hex stream(str)
def bytes_to_hexString(bs):
return ''.join(['%02x' % e for e in bs])
3. bytes 解码
bytes.fromhex(hex_str).strip(b'\xef\xbb\xbf').rstrip(b'\x00').decode('utf-8')
import json # 原生dict data_dict = {"a": "b", "a1": [{"a2": "b2"}, "c3"]} data_str = json.dumps(data_dict) data_byte = data_str.encode('utf8') data_hex = ''.join(['%02x' % b for b in data_byte]) print(data_hex) data_byte1 = bytes.fromhex(data_hex) data_str1 = data_byte1.strip(b'\xef\xbb\xbf').rstrip(b'\x00').decode('utf-8').replace("\n", "").replace("\t", "") data_dict1 = json.loads(data_str1) print(type(data_dict1), data_dict1)
开源永流传