Skip to content

Instantly share code, notes, and snippets.

@ASPePeX
Created July 24, 2018 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ASPePeX/1e1323691395869bf1f8f63170dbad1f to your computer and use it in GitHub Desktop.
Save ASPePeX/1e1323691395869bf1f8f63170dbad1f to your computer and use it in GitHub Desktop.
Casting Span<T> Example - int to byte and back
using System;
using System.Runtime.InteropServices;
namespace SpanCast
{
class Program
{
static void Main(string[] args)
{
//preparing test data
var intArr = new int[] {1,2,3,4,5,6};
var byteArr = new byte[intArr.Length * sizeof(int)];
Buffer.BlockCopy(intArr, 0, byteArr, 0, byteArr.Length);
//casting the byte array to Span<byte>
ReadOnlySpan<byte> byteSpan = byteArr;
//casting Span<byte> to Span<int>
ReadOnlySpan<int> intSpan = MemoryMarshal.Cast<byte, int>(byteSpan);
//and back to a single int
int justOneInt = intSpan[2];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment