如何使用Python将不同类型的数据打包成二进制数据

时间:2014-11-02 00:39:50

标签: python c networking

假设有一个用户定义的协议如下:

The protocol:

 ------------- ------------- ---------------- -----------------
|   Seqno.    |      ip     |       port     |    user name    |
| int, 4 bytes| int, 4 bytes| short, 2 bytes | string, 50 bytes|


the [user name] field stores a string ending with zero,    
if the string length is less than 50 bytes, padding with zeros.

通常我会用C语言打包这些字段:

//Pseudo code
buffer = new char[60];
memset(buffer, 0, 60);

memcpy(buffer, &htonl(Seqno), 4);
memcpy(buffer+4, &htonl(ip), 4);
memcpy(buffer+4, &htons(port), 2);
memcpy(buffer+2, Usrname.c_str(), Usrname.length() + 1);

但是我们如何在python中打包协议数据呢?我是python的新手。

1 个答案:

答案 0 :(得分:1)

使用struct module

import struct

binary_value = struct.pack('!2IH50s', seqno, ip, port, usrname)

这包含2个4字节无符号整数,一个2字节无符号短整数和一个50字节字符串,分为60字节,网络(大端)字节排序。字符串将用空值填充以构成长度:

>>> import struct
>>> seqno = 42
>>> ip = 0xc6fcce10
>>> port = 80
>>> usrname = 'Martijn Pieters'
>>> struct.pack('!2IH50s', seqno, ip, port, usrname)
'\x00\x00\x00*\xc6\xfc\xce\x10\x00PMartijn Pieters\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

Python的字符串表示对ASCII可打印范围内的任何字节使用ASCII字符,对于大多数其他字节点使用\xhh,因此42变为\x00\x00\x00*