.Net Core 中的 Big-Endian 处理 [英] Big-Endian handling in .Net Core
问题描述
是否有支持 .Net Core 的 BitConverter
或其他类,我可以读取整数和其他值作为 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
它包含用于 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 处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!