Python struct模块
由于Python没有专门处理字节的数据类型,Python提供了一个struct模块来解决bytes和其他二进制数据类型的转换。 struct的pack函数把任意数据类型变成bytes import struct r = struct . pack ( '>l' , 99999999 ) print ( r ) pack的第一个参数是处理指令 > 表示字节顺序是大端序 < 表示小端序 ! 网络序列, 也是大端序 格式 类型 字节 i int 4 c char 1 f float 4 d double 8 s char[] 1 I unsigned int h short 2 ? bool 1 q long long 8 Q unsigned long long 8 L unsigned long 4 H unsigned short 2 常用的两个api就是 pack() 与 unpack() uppack返回一个tuple, import struct s = 'moddemod' . encode ( ) r1 = struct . pack ( '>8s' , s ) r2 , = struct . unpack ( '>8s' , r1 ) print ( r2 . decode ( ) ) # moddemod 这里其实是对应c语言的数据类型,因为数据传输都是字节流传输的