2012-03-16 37 views
3

對於閱讀C#中的二進制文件,我確實很困惑。 我有C++代碼讀取二進制文件:將二進制讀取函數從C++轉換爲C#

FILE *pFile = fopen(filename, "rb");  
uint n = 1024; 
uint readC = 0; 
do { 
    short* pChunk = new short[n]; 
    readC = fread(pChunk, sizeof (short), n, pFile);  
} while (readC > 0); 

,並讀了以下數據:

-156, -154, -116, -69, -42, -36, -42, -41, -89, -178, -243, -276, -306,... 

我試圖把這段代碼轉換爲C#,但無法讀取這些數據。這裏是代碼:

using (var reader = new BinaryReader(File.Open(filename, FileMode.Open))) 
{ 
    sbyte[] buffer = new sbyte[1024];     
    for (int i = 0; i < 1024; i++) 
    { 
     buffer[i] = reader.ReadSByte(); 
    }     
} 

,我也得到了以下數據:

100, -1, 102, -1, -116, -1, -69, -1, -42, -1, -36 

我怎樣才能得到類似的數據?

+0

在C++中,你正在閱讀的每個實體作爲'short',其爲2個字節,而在C#中,正在閱讀的每個實體作爲'sbyte'這是1個字節。 – Jason 2012-03-16 09:12:32

+0

@Jason肯定在C++中'short'的大小沒有完全定義; p但是:我不反對。你應該添加這個答案。 – 2012-03-16 09:12:43

+0

我不知道,沒有C++經驗;/ – Jason 2012-03-16 09:13:06

回答

2

短不是一個有符號的字節,它是一個有符號的16位值。

short[] buffer = new short[1024];     
for (int i = 0; i < 1024; i++) { 
    buffer[i] = reader.ReadInt16(); 
} 
2

這是因爲在C++中你正在閱讀短褲,而在C#中你正在閱讀有符號字節(這就是爲什麼SByte的意思)。您應該使用reader.ReadInt16()

1

您應該使用相同的數據類型來獲取正確的輸出或轉換爲新類型。

在C++中,您正在使用short。 (我想這個文件也是用short寫的),所以在c#中使用short本身。或者您可以使用Sytem.Int16

您會得到不同的值,因爲shortsbyte不等效。 short是2個字節,並且Sbyte是1個字節

using (var reader = new BinaryReader(File.Open(filename, FileMode.Open))) 
{ 
    System.Int16[] buffer = new System.Int16[1024];     
    for (int i = 0; i < 1024; i++) 
    { 
     buffer[i] = reader.ReadInt16(); 
    }     
} 
相關問題