Reputation: 41
I'm looking to convert a Memory<Byte>
to some other type (double, int...) while trying to eliminate allocation (until the final place where the value goes).
I figure out how to get the value of a bit in a byte but I can't seem to figure out how to do it for a double or int. I want to avoid using .ToArray as it would perform a heap allocation.
[EDIT] Also to make things even easier, I need to perform a byte swap prior to conversion.
var buffer = GC.AllocateArray<byte>(1024, true);
var bufferMem = buffer.AsMemory();
//Something put data in bufferMem
var boolValue = bufferMem
.Slice(0, 1)
.Span[0]
.GetBit();
public static bool GetBit(this byte b, int bitIndex)
{
return (b & (1 << bitIndex)) != 0;
}
Thank you for your help
Upvotes: 1
Views: 449
Reputation: 8700
To work with the elements of a Memory<T>
, you normally get a Span<T>
from it. That can be interpreted as a span of a different type, provided that T
is unmanaged (i.e. recursively does not contain references types).
var buffer = GC.AllocateArray<byte>(1024, true);
var bufferMem = buffer.AsMemory();
//Something put data in bufferMem
var bytes = bufferMem.Span;
// Re-interpret
var doubles = MemoryMarshal.Cast<byte, double>(bytes);
This is allocation-free and highly efficient.
Upvotes: 0