【问题标题】:Use variable value as bytes array in Python在 Python 中使用变量值作为字节数组
【发布时间】:2014-10-29 09:28:12
【问题描述】:

我想在 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 个字节并循环复制它

【问题讨论】:

  • 您在执行正常的 XML-RPC 吗?你有什么理由不能使用xmlrpclib
  • 它是自定义 XMLRPC,加密和 zlibbed。我应该按原样支持它的协议

标签: python python-bytearray


【解决方案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"))

另见:

【讨论】:

  • 奇怪,但是header总是0
  • 标头在那里,您可能正在查看填充,即 0。当 result = "good day"to_send = b'\x08\x00\x00\x00good day' 时。您也可以使用to_send[0] 进行检查。如果您希望填充在数字之前,您可以使用&gt; 而不是@
  • 谢谢!这正是我所需要的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-28
  • 2019-05-27
  • 2018-10-30
相关资源
最近更新 更多