从C#流读取一个无符号的24位整数 [英] Reading an unsigned 24-bit integer from a C# stream
本文介绍了从C#流读取一个无符号的24位整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是阅读使用BinaryReader一个C#流无符号的24位整数的最佳途径?
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?
推荐答案
你的代码的一些狡辩
- 你质疑和签名说未签名的,但你从函数返回一个符号值
-
字节
在.NET是无符号的,但你使用算术符号值迫使以后使用Math.Abs
的。使用所有未签名的计算,以避免这种情况。 - 恕我直言,这是清洁转向使用移位运算代替乘法位。
- 静静地捕捉异常可能是这里的错误观念。
- 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;
}
}
这篇关于从C#流读取一个无符号的24位整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文