raw decoder for protobufs format

前端 未结 4 1898
别那么骄傲
别那么骄傲 2020-12-02 18:42

I\'d like to find a way to convert a binary protobuf message into a human readable description of the contained data, without using the .proto files.

The background

4条回答
  •  有刺的猬
    2020-12-02 19:29

    If you happen to have a binary file containing (multiple?) length-prefixed protobuf messages, protoc ‒‒decode_raw < file cannot parse it because of the length prefixes. A simple way around that is to split the file into its consecutive messages and then convert each with protoc.

    My take:

    var fs = File.OpenRead(filename));
    var buffer = new byte[4096];
    int size;
    for (int part = 1; Serializer.TryReadLengthPrefix(fs, PrefixStyle.Base128, out size); part++) {
      long startPosition = fs.Position;
      using (var writer = File.OpenWrite(string.Format("{0}[{1}].pb", filename, part))) {
        for (int bytesToRead = size; bytesToRead > 0; ) {
          int bytesRead = fs.Read(buffer, 0, Math.Min(bytesToRead, buffer.Length));
          bytesToRead -= bytesRead;
          if (bytesRead <= 0) // End of file.
            break;
          writer.Write(buffer, 0, bytesRead);
        }
      }
    }
    

提交回复
热议问题