gpt4 book ai didi

python - 如何使用 python protobuf 2.5.0 设置字节字段?

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:58 24 4
gpt4 key购买 nike

有消息

message MyMessage {
required bytes mybytesfield = 1;
}

我用

生成了 python 代码
protoc -I. --python_out=. message.proto

并尝试像这样添加字节字段(Python 2.7.6):

import message_pb2 as mpb

msg = mpb.MyMessage()
msg.mybytesfield = bytes([0xDE, 0xAD])
# msg.mybytesfield = b'\xDE\xAD'
with open("output.bin", "w") as f:
f.write(msg.SerializeToString())

但从 hexdump -C 的输出来看,它似乎编码了文字 [222, 173] 而不是 dead

0xDEAD 写入 mybytesfield 的正确方法是什么?

最佳答案

bytes([0xDE, 0xAD]) 在 Python 2.7 中不转换为 b'\xde\xad' 而是转换为 '[222, 123 ]' 是一个包含 10 个字符的字符串,它是数组的字符串表示形式。

bytes 在 Python 2.7 中是 str 的别名,在 Python 3.x 中 bytes 做“预期”的事情并且 bytes([0xde, 0xad]) 产生 b'\xde\xad

设置 mybytesfield 的正确方法如下:

msg.mybytesfield = b'\xDE\xAD' #literal

或者如果您首先需要一个整数列表/数组:

msg.mybytesfield = ''.join(chr(item) for item in [0xDE, 0xAD]) 

关于python - 如何使用 python protobuf 2.5.0 设置字节字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30707056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com