在Python中使用变量值作为字节数组

时间:2014-10-29 09:28:12

标签: python python-bytearray

我想在Python中实现套接字客户端。服务器期望前8个字节包含总传输大小(以字节为单位)。在C客户端,我这样做了:

uint64_t total_size = zsize + sizeof ( uint64_t );
uint8_t* xmlrpc_call = malloc ( total_size );
memcpy ( xmlrpc_call, &total_size, sizeof ( uint64_t ) );
memcpy ( xmlrpc_call + sizeof ( uint64_t ), zbuf, zsize );

zsize和zbuff是我要传输的大小和数据。 在python中,我创建了这样的字节数组:

cmd="<xml>do_reboot</xml>"
result = deflate (bytes(cmd,"iso-8859-1"))
size = len(result)+8

在Python中填充标题的最佳方法是什么?不将值分隔为8个字节并将其复制到循环

1 个答案:

答案 0 :(得分:1)

您可以使用struct模块,它会将您的数据打包成您想要的格式的二进制数据

import struct
# ...your code for deflating and processing data here...

result_size = len(result)
# `@` means use native size, `I` means unsigned int, `s` means char[].
# the encoding for `bytes()` should be changed to whatever you need
to_send = struct.pack("@I{0}s".format(result_size), result_size, bytes(result, "utf-8"))

另见: