Reading an unsigned 24-bit integer from a C# stream
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() & 0x开发者_如何学编程FF));
}
catch
{
return 0;
}
}
Is there any better way to do this?
Some quibbles with your code
- You question and signature say unsigned but you return a signed value from the function
Byte
in .Net is unsigned but you're using signed values for arithmetic forcing a later use ofMath.Abs
. Use all unsigned calculations to avoid this.- IMHO it's cleaner to shift bits using shift operators instead of multiplication.
- Silently catching the exception is likely the wrong idea here.
I think it's more readable to do the following
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;
}
}
This looks pretty elegant to me.
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;
}
}
精彩评论