我这个为什么突然需要学习字节流和数据对象之间的转换呢……因为我们公司有一个用多种语言来处理数据的需求,最终选择的解决方案是直接用字节流来存储数据。所以我现在需要用Python 3来手动解码一下这个数据,故有此文。
Python 3中字节流对象是b
开头的字符串。字节流本质上是一串数字(0-256之间的数字),所以一个字节流对象可以转换成一个数字列表。
文章目录
1. 字符串 → 字节流:str.encode()
example_str="这是一串示例性字符串"
example_bytes=example_str.encode()
number_bytes=list(example_bytes)
str.encode()
入参:
encoding: str = "utf-8"
errors: str = "strict"
example_bytes:b'\xe8\xbf\x99\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xb2\xe7\xa4\xba\xe4\xbe\x8b\xe6\x80\xa7\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2'
number_bytes:
[232, 191, 153, 230, 152, 175, 228, 184, 128, 228, 184, 178, 231, 164, 186, 228, 190, 139, 230, 128, 167, 229, 173, 151, 231, 172, 166, 228, 184, 178]
2. 字节流 → 字符串:bytes.decode()
number_bytes=[232, 191, 153, 230, 152, 175, 228, 184, 128, 228, 184, 178, 231, 164, 186, 228, 190, 139, 230, 128, 167, 229, 173, 151, 231, 172, 166, 228, 184, 178]
example_bytes=bytes(number_bytes)
example_str=example_bytes.decode()
入参和encode()
的相同
3. 数字 + format → 字节流:struct.pack()
以float数据(format为'f'
,用4个字节表示的数据)为例:
import struct
bytes_flow=struct.pack("f", 298.76953125) # b'\x80b\x95C'
number_bytes_flow=list(bytes_flow) # [128, 98, 149, 67]
这里的format是以C语言里的对象格式为准。毕竟Python里面的数字就只有int和float格式嘛。
format全部的表格可以参考:https://docs.python.org/3/library/struct.html#format-characters
其中Standard size就是一个这个格式的数据对象需要用几个字节来表示。
4. 字节流 + format → 数字:struct.unpack()
import struct
float_num = struct.unpack("f", bytes([128, 98, 149, 67])) # 返回值是一个元组对象,其中第一个元素就是我们所需的数字:(298.76953125,)