derodevil
derodevil

Reputation: 1071

Serialize or encode proto member to byte array

I have proto members that look like this

String = "1324211127562612736"
Varint = 1
Varint = 10000000000

How could I serialize to byte array where the result should look like this?

0x0a, 0x13, 0x31, 0x33, 0x32, 0x34, 0x32, 0x31, 0x31, 0x31, 0x32, 0x37, 0x35, 0x36, 0x32, 0x36, 0x31, 0x32, 0x37, 0x33, 0x36, 0x20, 0x01, 0x28, 0x80, 0xc8, 0xaf, 0xa0, 0x25

Upvotes: 1

Views: 1277

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062502

By running the hex 0A133133323432313131323735363236313237333620012880C8AFA025 through https://protogen.marcgravell.com/decode, we can see that we have:

Field #1: 0A String Length = 19, Hex = 13, UTF8 = "1324211127562612 ..." (total 19 chars)
Field #4: 20 Varint Value = 1, Hex = 01
Field #5: 28 Varint Value = 10000000000, Hex = 80-C8-AF-A0-25

which tells us the field numbers; so, let's try:

[ProtoContract]
class Foo
{
    [ProtoMember(1)]
    public string X { get; set; }

    [ProtoMember(4)]
    public int Y { get; set; }

    [ProtoMember(5)]
    public long Z { get; set; }
}

and we can generate the payload via serialization:

var foo = new Foo { X = "1324211127562612736", Y = 1, Z = 10000000000 };
using var ms = new MemoryStream();
Serializer.Serialize(ms, foo);
if (!ms.TryGetBuffer(out var buffer))
{   // in reality we should never hit this - TryGetBuffer should work
    buffer = new ArraySegment<byte>(ms.ToArray());
}
Console.WriteLine(BitConverter.ToString(buffer.Array, buffer.Offset, buffer.Count));

which outputs:

0A-13-31-33-32-34-32-31-31-31-32-37-35-36-32-36-31-32-37-33-36-20-01-28-80-C8-AF-A0-25

Upvotes: 1

Related Questions