Files
WCS/Cowain.Base/Extensions/ShortArrayExtensions.cs
2026-03-02 09:08:20 +08:00

27 lines
885 B
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Buffers.Binary;
namespace Cowain.Base.Extensions;
public static class ShortArrayExtensions
{
/// <summary>
/// 将 short[] 转换为 byte[],并可选择大小端。
/// </summary>
/// <param name="src">源数组</param>
/// <param name="asLittleEndian">true 为小端false 为大端</param>
public static byte[] ToByteArray(this short[] src, bool asLittleEndian = true)
{
if (src == null) throw new ArgumentNullException(nameof(src));
var dst = new byte[src.Length * sizeof(short)];
for (int i = 0; i < src.Length; i++)
{
var span = dst.AsSpan(i * sizeof(short));
if (asLittleEndian)
BinaryPrimitives.WriteInt16LittleEndian(span, src[i]);
else
BinaryPrimitives.WriteInt16BigEndian(span, src[i]);
}
return dst;
}
}