use*_*200 13 c# arrays type-conversion
我有这种代码
static void Main(string[] args)
{
byte[] array = new byte[2] { 0x00, 0x1f };
Console.WriteLine(BitConverter.ToInt32(array, 0));
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用.它引发了一个异常:
目标数组不够长,无法复制集合中的所有项目.检查数组索引和长度.
怎么了?
An Int32
由4个字节组成,但数组只有2个.解决此问题的方法之一是首先转换为Int16
然后转换为Int32
Console.WriteLine((Int32)(BitConverter.ToInt16(array, 0)));
Run Code Online (Sandbox Code Playgroud)
请注意,在此特定用法中,转换为Int32
from Int16
不会更改任何内容,因为数字打印相同.
这是一个老问题,但对于 .NET Core / .NET Standard > 2.1 有新的解决方案:
该类为此System.Buffers.Binary.BinaryPrimitives
目的提供了两个静态方法。ReadInt32BigEndian
ReadInt32LittleEndian
使用这些方法有两个优点:
Span<T>
这可能是一种性能优势,具体取决于具体情况。