java - Serializing/Deserializing a standalone integer using protocol buffers -
up now, i've been using protocol buffers serialize , deserialize objects using code-generated classes.
now attempting serialize , deserialize single 64-bit integer. problem is, i'm getting different results in java , c#.
here's how i'm doing 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's how i'm doing 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); } }
the java code converted number 9876
[0x94, 0x4d]
the c# code converted number 9876
[0x08, 0x94, 0x4d]
how do both com.google.protobuf
, protobuf.net
produce identical outputs?
the protobuf.net method protobuf.serializer.serialize
forces field header (field number=1) stream. that's way can perform serialization; method invokes number of internal methods not publicly available.
the solution i'm using change java code include field header.
here new java code.
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(); }
the changes i've made are:
- when computing required buffer size, include tag size
- instead of
codedoutputstream.writeint64notag
, callcodedoutputstream.writeint64
- when reading back, call
codedoutputstream.readtag
before callingcodedoutputstream.readint64
Comments
Post a Comment