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
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);
}
}
}