簡體   English   中英

使用協議緩沖區序列化/反序列化獨立整數

[英]Serializing/Deserializing a standalone integer using protocol buffers

到目前為止,我一直在使用Protocol Buffers來使用代碼生成的類來序列化和反序列化對象。

現在我試圖序列化和反序列化一個64位整數。 問題是,我在Java和C#中得到了不同的結果。

這是我在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;
}

以下是我在C#中使用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代碼將數字9876轉換為[0x94, 0x4D]

C#代碼將數字9876轉換為[0x08, 0x94, 0x4D]

我如何做到這一點,以便com.google.protobufprotobuf.net產生相同的輸出?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM