加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core – .Net Core中的Big-Endian处理

发布时间:2020-12-16 09:55:09 所属栏目:asp.Net 来源:网络整理
导读:是否有BitConverter或其他支持.Net Core的类,我可以读取整数和其他值作为Big Endian编码? 我不需要编写一组辅助方法: int GetBigEndianIntegerFromByteArray(byte[] data,int startIndex) { return (data[startIndex] 24) | (data[startIndex + 1] 16) | (
是否有BitConverter或其他支持.Net Core的类,我可以读取整数和其他值作为Big Endian编码?

我不需要编写一组辅助方法:

int GetBigEndianIntegerFromByteArray(byte[] data,int startIndex) {
    return (data[startIndex] << 24)
         | (data[startIndex + 1] << 16)
         | (data[startIndex + 2] << 8)
         | data[startIndex + 3];
}

解决方法

从.NET Core 2.1开始,在静态类System.Buffers.Binary.BinaryPrimitives中有一个统一的API

它包含ReadOnlySpan的API和原始类型的直接反字节序(short / ushort,int / uint,long / ulong)

private void GetBigEndianIntegerFromByteArray(ReadOnlySpan<byte> span,int offset)
{
    return BinaryPrimitives.ReadInt32BigEndian(span.Slice(offset));
}

System.Buffers.Binary.BinaryPrimitives类是.NET Core 2.1的一部分,不需要NuGet包

此类还包含Try …方法

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读