Span<T> - byte to int conversions - Update

Updating the Span conversion examples with the updated API

Published on 13 September 2018

Earlier in the year when Span was announced and early sight details were released I read an article by Stephen Toub on C# - All About Span: Exploring a New .NET Mainstay.

Part of the article was about how to convert between different T's in the spans and it didn't go into too much detail about the how so I wrote an post which shows my investigation and examples.

I was recently contacted on twitter to say that the article helped the developer who sent me a message. It was nice to hear that my post helped them but it also highlighted that the API for Span has changed since the early work so I wanted to update my example from before and identify the changes.

Originally the converting from Span<byte> to Span<int> was performed through using an extension method called NonPortableCast.

Span<int> asInts = asBytes.NonPortableCast<byte,int>();

This was not very clear or intuitive to find so I am glad this has been updated.

The action of converting is now performed by the MemoryMarshal class through the Cast method.

Span<int> asInts = MemoryMarshal.Cast<byte, int>(asBytes);

In addition to the converting functionality the ability to read the value from the Span<T> to the U directly has been updated via the MemoryMarshal class as well.

int i = MemoryMarshal.Read<int>(asBytes);

Full example with the updates:

// set a plain integer and convert it to a byte array
int number = 42;
byte[] numberBytes = BitConverter.GetBytes(number);

// now through the implicit casting convert to a span<byte>
Span<byte> asBytes = numberBytes;

// read the value from the bytes
int i = MemoryMarshal.Read<int>(asBytes);

// now using the MemoryMarshal interopservice
Span<int> asInts = MemoryMarshal.Cast<byte, int>(asBytes);

// check that it's all pointing to the same pointer references
Assert.Equal(42, asInts[0]);
Assert.Equal(number, asInts[0]);
Assert.Equal(42, i);
asInts[0] = 123456;
int converted = BitConverter.ToInt32(numberBytes, 0);
Assert.Equal(123456, converted);

Hope this helps further people!

Any questions/comments then please contact me on Twitter @WestDiscGolf.

If it does help, please let me know!