2010-08-24 71 views
3

使用BinaryReader從C#流中讀取一個無符號的24位整數的最佳方法是什麼?從C#流中讀取一個無符號的24位整數

到目前爲止,我用這樣的:

private long ReadUInt24(this BinaryReader reader) 
{ 
    try 
    { 
     return Math.Abs((reader.ReadByte() & 0xFF) * 256 * 256 + (reader.ReadByte() & 0xFF) * 256 + (reader.ReadByte() & 0xFF)); 
    } 
    catch 
    { 
     return 0; 
    } 
} 

有沒有什麼更好的方法來做到這一點?

回答

10

與您的代碼的一些狡辯

  • 你提問和簽名說無符號,但你從功能
  • 在.net Byte是無符號的返回一個符號值,但你使用符號值算術強制以後使用Math.Abs。使用所有無符號計算來避免這種情況。
  • 恕我直言,它使用移位運算符而不是乘法來移位。
  • 無聲捕捉異常可能是錯誤的想法。

我認爲這是更具可讀性做到以下幾點

private static uint ReadUInt24(this BinaryReader reader) { 
    try { 
     var b1 = reader.ReadByte(); 
     var b2 = reader.ReadByte(); 
     var b3 = reader.ReadByte(); 
     return 
      (((uint)b1) << 16) | 
      (((uint)b2) << 8) | 
      ((uint)b3); 
    } 
    catch { 
     return 0u; 
    } 
} 
+0

是的,更具可讀性,但我想知道在這裏默默地捕捉異常是否是一個好主意? (當然,我不知道如何使用這種方法,但它並沒有留下好的感覺)。 – 2010-08-24 17:35:58

+0

@ 0xA3同意它可能是錯誤的想法,並在我的編輯中指出。 – JaredPar 2010-08-24 17:37:54

+0

謝謝,但爲什麼在這裏很容易捕捉到可能是錯誤想法的異常? – 2010-08-24 17:42:50

1

這看起來很優雅的我。

private static long ReadUInt24(this BinaryReader reader) 
{ 
    try 
    { 
    byte[] buffer = new byte[4]; 
    reader.Read(buffer, 0, 3); 
    return (long)BitConverter.ToUInt32(buffer, 0); 
    } 
    catch 
    { 
    // Swallowing the exception here might not be a good idea, but that is a different topic. 
    return 0; 
    } 
} 
+0

我更喜歡JaredPar的答案的主要原因是顯式放置字節。例如,如果字節的順序不同,他的解決方案很容易修復,但是這會導致一些問題,試圖解決這個問題。 – Dolphin 2010-08-24 18:06:22

+0

JaredPar的答案也執行得更快。 – 2010-08-24 18:22:11

相關問題