Reading a 24 bit unsigned integer from a C # stream

What is the best way to read a 24 bit unsigned integer from a C # stream using BinaryReader?

So far I have used something like this:

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

Is there a better way to do this?

+3
source share
2 answers

Some puns with your code

  • You ask a question and sign the word unsigned, but you return a signed value from the function
  • Bytein .Net has no sign, but you use signed values ​​for arithmetic, forcing to use Math.Absin the future. Use all unsigned calculations to avoid this.
  • IMHO it is cleaner to shift bits using shift operators instead of multiplication.
  • , , .

,

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

.

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

Source: https://habr.com/ru/post/1761360/


All Articles