Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Int32 from Span<byte>

Tags:

c#

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());
like image 893
Wjdavis5 Avatar asked May 12 '26 03:05

Wjdavis5


2 Answers

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().

like image 196
Jeff Dammeyer Avatar answered May 13 '26 16:05

Jeff Dammeyer


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");
like image 34
CajunCoding Avatar answered May 13 '26 16:05

CajunCoding