int[] original = { 1, 2, 3, 4 }, copy;
byte[] bytes;
using (var ms = new MemoryStream())
{
using (var writer = new BinaryWriter(ms))
{
writer.Write(original.Length);
for (int i = 0; i < original.Length; i++)
writer.Write(original[i]);
}
bytes = ms.ToArray();
}
using (var ms = new MemoryStream(bytes))
using (var reader = new BinaryReader(ms))
{
int len = reader.ReadInt32();
copy = new int[len];
for (int i = 0; i < len; i++)
{
copy[i] = reader.ReadInt32();
}
}
雖然我個人只是從無線BinaryReader
的流中讀取。
其實,嚴格來講,如果是我,我會用我的own serializer,只是:
[ProtoContract]
public class Foo {
[ProtoMember(1, Options = MemberSerializationOptions.Packed)]
public int[] Bar {get;set;}
}
,因爲這將有稱爲字節順序,處理緩衝,並且將使用可變長度編碼,以幫助如果大部分數字都不是很大,就會減少膨脹。
(只是與樣本數據進行測試;通過protobuf的,而不是20 6個字節 - 當然這有助於我使用的數字都很小) – 2011-01-20 07:23:19