What is the best way to read an unsigned 24-bit integer from a C# stream using BinaryReader?
So far I 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 any better way to do this?
Some quibbles with your code
Bytein .Net is unsigned but you’re using signed values for arithmetic forcing a later use ofMath.Abs. Use all unsigned calculations to avoid this.I think it’s more readable to do the following