protobuf 编码

参考资料:

想法

Protocol buffers are Google's language-neutral, platform-neutral,extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler.
protobuf 编码的目的是为了减少传输数据量
1.使用二进制流(TLV)来表示信息
2.对于整数使用 Varint,负整数使用 ZigZag ,进一步减少字节数

代码运行参考

pip 安装

pip install grpcio-tools

使用下列指令编译 .proto 文件,会在当前目录生成 *_pb2.py*_pb2_grpc.py 文件,定义的 message 对象在 *_pb2.py 文件

python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. <目标 proto 文件>

示例
example.proto

syntax = "proto2";

package tutorial;

message Example {
    repeated int32 id = 1;
    repeated int32 pid = 2 [packed=true];
}

example.py

import example_pb2


demo = example_pb2.Example()
demo.id.extend([1,1,1])
demo.pid.extend([1,1,1])
print(demo.SerializeToString())
# 结果
# b'\x08\x01\x08\x01\x08\x01\x12\x03\x01\x01\x01'
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容