2012-05-30 36 views
1

我使用Visual Studio 2005和.Net20版本的protobuf-net r480。Protobuf-net在每個字節前將字節[]的數據序列化爲'00'

我嘗試按照一個例子,序列化一類的字符串,枚舉,int和字節[]數據如下

[ProtoContract] 
public class Proto_DemoMessage { 
    public enum ESSCommandType : int { 
     ClientServer = 0, 
     Broadcast = 10, 
     Assign = 11, 
    } 

    [ProtoMember(1, IsRequired = false)] 
    public string Name; 
    [ProtoMember(3, IsRequired = true)] 
    public ESSCommandType CommandType; 
    [ProtoMember(4, IsRequired = false)] 
    public int Code; 
    [ProtoMember(5, IsRequired = false)] 
    public byte[] BytesData; 

    public byte[] Serialize(){ 
     byte[] b = null; 
     using (MemoryStream ms = new MemoryStream()) { 
      Serializer.Serialize<Proto_DemoMessage>(ms, this); 
      b = new byte[ms.Position]; 
      byte[] fullB = ms.GetBuffer(); 
      Array.Copy(fullB, b, b.Length); 
     } 
     return b; 
    } 

而對於每個字段給值如下

Proto_DemoMessage inner_message = new Proto_DemoMessage(); 
inner_message.Name = "innerName"; 
inner_message.CommandType = Proto_DemoMessage.ESSCommandType.Broadcast; 
inner_message.Code = 11; 
inner_message.BytesData = System.Text.Encoding.Unicode.GetBytes("1234567890"); 

在調用inner_message.Serialize()之後,我將結果字節[]寫入文件。當我以十六進制模式打開文件來驗證它時,我發現byte []中的每個字節後面都有一個00填充。 結果是:

2A 14 31 00 32 00 33 00 34 00 35 00 36 00 37 00 38 00 39 00 30 00 

有什麼我做錯了嗎?我很感謝你的幫助。

+0

你讓我用你的'MemoryStream'代碼......你可以直接使用'.ToArray()' - 它會更加直接。但蟬是完全正確的;您將「BytesData」包含爲UTF-16;哪些*對於ASCII範圍字符具有零。這完全是自己造成的,通過'BytesData ='行 –

回答

3

一切都OK。您的字符串以UTF-16編碼。在這種編碼中,所有字符都是(至少)兩個字節寬。

+0

實際上,可能會有**兩個**問題!我把它收回!內存流使用**和**編碼不良。抱歉。我犯了一個錯誤。我放棄了 - 我誠摯的道歉。 –

+0

@MarcGravell不用擔心!但你真的讓我困惑了一會兒! :) –

+0

是的,對不起。 ...「不尋常的」MemoryStream複製代碼扔給我,我追趕了錯誤的領導。完全是我的不好。 –

1

,當我檢查,如果這些零確實是因爲Unicode編碼的,我也檢查了UTF8更緊湊(因爲它可以預期),所以使用

inner_message.BytesData = System.Text.Encoding.UTF8.GetBytes("1234567890"); 

可能會做一些很好的。

upd:或者根據Marc Gravell的建議真正使用string屬性。

+0

我會說:如果你想存儲一個字符串,比如「1234567890」,那麼*有一個字符串屬性*,並讓序列化器擔心編碼; p –

+0

@Marc Gravell:或者那個。它是否完全自動unicode功能開箱?它如何默認編碼? –

+0

是的,protobuf規範(由Google)明確指出UTF-8將用於字符數據,所以一個簡單的'string'可以正常工作,並且會根據您的答案通過UTF-8編碼。但自動。 –

相關問題