Been researching spans, memory etc . I'm trying to understand the intended method for getting an int out of a Span
Of all the blog posts I've read there was hinting of a NonPortableCast<T> method being implemented, but it appears that it has been removed.
I also read about it potentially being renamed to .Cast<T> on one of Marc Gravell's posts but again, I cant find it anywhere.
So given:
public ReadOnlySpan<byte> MessageBytes {get;set;}
public ReadOnlySpan<byte> ItemLengthBytes => MessageBytes.Slice(0,4);
How do I convert those 4 bytes to an int?
Here is what Im doing now, is this the correct way? Or is there a faster way?
public int ItemLength => Convert.ToInt32(ItemLengthBytes.ToArray());
In the most recent bits, the Cast method is now under System.Runtime.InteropServices.MemoryMarshal.
But if you intend to read out a single int, you probably want the Read method on that same type.
as such:
public int ItemLength => MemoryMarshal.Read<int>(ItemLengthBytes);
There's also BitConverter.ToInt32, which is more analagous to the older Convert apis.
public int ItemLength => BitConverter.ToInt32(ItemLengthBytes);
What you wrote will work as well, but it will lose a lot of the performance advantage of the Span, since you'll do an extra memory copy and heap allocation every time you use ToArray().
The prior answer notes MemoryMarshal.Read<int>()... which is correct but is a lower level API, if you want to have Endianness automatically handled then you can use the BinaryPrimitives class which ensures that Endianness is not an issue...
public int ItemLength => BinaryPrimitives.TryReadInt32LittleEndian(ItemLengthBytes, out var resultInt)
? resultInt
: throw new ArgumentException("Conversion to Int failed");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With