问题描述
是否存在 BitConverter
或其他支持.Net Core的类,我可以读取具有Big Endian编码的整数和其他值?
Is there a BitConverter
or other class that supports .Net Core that I can read integers and other values as having Big Endian encoding?
我不太需要编写一组辅助方法:
I don't feel good about needing to write a set of helper methods:
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
Since .NET Core 2.1 there is a unified API for this in static class System.Buffers.Binary.BinaryPrimitives
的统一API,它包含ReadOnlySpan的API和原始类型的直接逆字节序(short / ushort,int / uint,long / ulong)
It contains API for ReadOnlySpan and direct inverse endianness for primitive types (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程序包
System.Buffers.Binary.BinaryPrimitives class is a part of .NET Core 2.1 and no NuGet packages are needed
该类还包含Try ...方法
Also this class contains Try... methods
这篇关于.Net Core中的Big-Endian处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!