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)
| 归档时间: |
|
| 查看次数: |
2433 次 |
| 最近记录: |