我有一个方法可以转换 Span<byte>
至 int
:
int ConvertToInt32(Span<byte> buffer)
{
if (buffer.Length != 4)
{
// add zero-padding to the buffer
}
return BitConverter.ToInt32(buffer);
// or MemoryMarshal....
}
如果输入参数 ( buffer
) 长度为 4,则转换有效,但如果它少于 4 个字节,则无效。
我正在寻找一种非分配方法来执行此操作。
那么如何向 buffer
添加零填充呢?转换之前,还是有其他解决方案?
最佳答案
您可以使用 stackalloc
在堆栈上进行分配这应该比在堆上分配更便宜,并且是高性能场景 AFAIK 中的常用方法:
Span<byte> buffer = stackalloc byte[3] {0,0,1};
if (buffer.Length != 4)
{
Span<byte> interimBuffer = stackalloc byte[4];
// ..
}
请注意,您可以转换为具有相应大小的类型,然后转换为 int
:
if (buffer.Length == 2)
{
var int16 = (int)BitConverter.ToInt16(buffer);
}
但由于分支,它的性能可能会更差。
也不要忘记计算机体系结构的字节序 as written in the docs .
关于c# - 如何在不分配内存的情况下向单个 Span<byte> 添加零填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75189838/