源码来自于 protobuf 3.5
//TestStruct.proto
message Pos{
uint32 x = 1;
uint32 y = 2;
}
Pos p;
p.set_x(1);
std::string s1 = p.SerializeAsString();
可以看到 s1.size() = 2
查看内存得到 十六进制为 0x 08 01 二进制位 00001000 0000 0001
查看生成的 TestStruct.pb.cc 文件
来看看 Pos::SerializeWithCachedSizes 的实现
// optional uint32 x = 1 [default = 0];
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->x(), output);
从头文件已经得知 0x00000001u 表示 x字段的编号
::google::protobuf::internal::WireFormatLite::WriteUInt32 函数的意思是把编号为1 的字段 写到stream
在 write_format_lite.cc 里找到
void WireFormatLite::WriteInt32(int field_number, int32 value,
io::CodedOutputStream* output) {
WriteTag(field_number, WIRETYPE_VARINT, output);
WriteInt32NoT