平时的开发中使用pb格式协议较多,大致了解了一下pb的编解码,即序列化和反序列化。
本文参考官方文档:https://developers.google.com/protocol-buffers/docs/encoding?hl=zh-cn
先看简单一个示例:
message Test1
{
required uint32 t = 1;
}
message Test2
{
required uint32 a = 1;
required Test1 test = 2;
optional uint32 b = 3;
optional bytes s = 4;
repeated uint32 list = 5;
}
//定义一个Test2对象,并设置字段值
Test2 test2;
test2.set_a(10);
Test1 *test1 = test2.mutable_test();
test1->set_t(150);
test2.set_s("test");
test2.add_list(300);
test2.add_list(500);
将test2序列化后的结果打印出来, 可发现其结果为(十六进制):08 0a 12 03 08 96 01 22 04 74 65 73 74 28 ac 02 28 f4 03
要想了解如何能够得到这样一串二进制或者根据这串二进制还原出对应的pb数据,就需要了解pb的编解码过程。
在编码过程中,pb会将message中的每个字段序列化成一对key-value,即message序列化后的结果是一系列的key-value。key由字段的tag和type决定(tag是字段的序号,例如a = 1中的1、list = 5中的5;type是字段的类型,例如uint32、bytes……),value是字段值经过一定的编码后的内容。