Serialize / Deserialize an Isolated Whole Using Protocol Buffers

So far, I have used protocol buffers to serialize and deserialize objects using code-generated classes.

Now I am trying to serialize and deserialize a single 64-bit integer. The problem is that I get different results in Java and C #.

This is how I do it in Java ....

private static byte[] convertLongToByteArray(long value) throws IOException {
    int size = CodedOutputStream.computeInt64SizeNoTag(value);
    byte[] buffer = new byte[size];
    CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(buffer);
    codedOutputStream.writeInt64NoTag(value);
    codedOutputStream.flush();
    codedOutputStream.checkNoSpaceLeft();
    return buffer;
}

And here is how I do it in C # using protobuf.net:

public void SerializeLongValue()
{
    long n = 9876;
    byte[] memoryBuffer = null;
    using (MemoryStream destination = new MemoryStream())
    {
        ProtoBuf.Serializer.Serialize(destination, n);
        destination.Flush();
        memoryBuffer = destination.ToArray();
    }

    using (MemoryStream source = new MemoryStream(memoryBuffer))
    {
        long result = ProtoBuf.Serializer.Deserialize<long>(source);
        Assert.AreEqual(n, result);
    }
}

Java code converted number 9876to[0x94, 0x4D]

C # code converts a number 9876to[0x08, 0x94, 0x4D]

How to do it, how to com.google.protobuf, and protobuf.netwere given identical outputs?

+4
1

protobuf.net ProtoBuf.Serializer.Serialize ( = 1) . ; , .

, , - Java, .

Java-.

private static byte[] convertLongToByteArray(long value) throws IOException {
    int size = CodedOutputStream.computeTagSize(1) + CodedOutputStream.computeInt64SizeNoTag(value);
    byte[] buffer = new byte[size];
    CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(buffer);
    codedOutputStream.writeInt64(1, value);
    codedOutputStream.flush();
    codedOutputStream.checkNoSpaceLeft();
    return buffer;
}

public static long convertByteArrayToLong(byte[] byteArray) throws IOException {
    CodedInputStream codedInputStream = CodedInputStream.newInstance(byteArray);
    codedInputStream.readTag();
    return codedInputStream.readInt64();
}

, , :

  • CodedOutputStream.WriteInt64NoTag CodedOutputStream.WriteInt64
  • CodedOutputStream.ReadTag CodedOutputStream.ReadInt64
+2

Source: https://habr.com/ru/post/1627705/


All Articles