2011-01-20 57 views
1

好吧,我已經使用BinaryWriter將文件轉換爲二進制格式。格式是:從二進制格式文件讀取32位整數的數組?

整數的數量,後跟整數。

因此,代碼將是這樣的:

readLineOfNumbers() { 
    count = read(); 
    int[] a = read(count ints); 
    return a; 
} 

難道我用BinaryReader在?我能看到的最接近的東西是將所有東西都讀入一個byte []中,但是我怎樣才能使它成爲一個int數組?這一切都必須非常有效地完成。我需要緩衝等等。

回答

1

我不知道BinaryReader內的任何東西,恐怕它會讀取整數數組。如果讀入字節數組,則可以使用Buffer.BlockCopy將這些字節複製到int[],這可能是最快的轉換形式 - 儘管它依賴於處理器的字節順序適合您的數據。

你有沒有試過只是循環,根據需要調用BinaryReader.ReadInt32()多少次,讓文件系統做緩衝?如果你認爲這會有所幫助的話,你總是可以添加一個帶有大緩衝區的BufferedStream

1
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;} 
} 

,因爲這將有稱爲字節順序,處理緩衝,並且將使用可變長度編碼,以幫助如果大部分數字都不是很大,就會減少膨脹。

+0

(只是與樣本數據進行測試;通過protobuf的,而不是20 6個字節 - 當然這有助於我使用的數字都很小) – 2011-01-20 07:23:19

2

如果您使用的BinaryWriter創建文件,它是有道理的使用BinaryReader在

讀它

喜歡的東西:

private static int[] ReadArray(BinaryReader reader) 
    { 
     int count = reader.ReadInt32(); 
     int[] data = new int[count]; 
     for (int i = 0; i < count; i++) 
     { 
      data[i] = reader.ReadInt32(); 
     } 
     return data; 
    } 
相關問題