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

2024-03-28 20:56:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python实现socket客户机。服务器希望前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字节,并在循环中复制它


Tags: 服务器cmdsize客户机字节xmlsocketresult
1条回答
网友
1楼 · 发布于 2024-03-28 20:56:54

您可以使用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"))

另请参见:

相关问题 更多 >