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

Alo*_*kin 3 c# data-structures

使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Jar*_*Par 10

你的代码有些狡辩

  • 您的问题和签名说无符号但您从函数返回一个有符号值
  • Byte在.Net中是无符号的,但是您使用有符号值来强制稍后使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)