从C#流中读取无符号的24位整数

使用BinaryReader从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; } } 

有没有更好的方法来做到这一点?

你的代码有些狡辩

  • 您的问题和签名说无符号,但您从函数返回一个有符号值
  • .Net中的Byte是无符号的,但是您使用带符号的值来强制稍后使用Math.Abs 。 使用所有未签名的计算来避免这种情况。
  • 恕我直言,使用移位运算符而不是乘法来移位位更清晰。
  • 默默地抓住exception可能是错误的想法。

我认为执行以下操作更具可读性

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

这看起来很优雅。

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