Created
July 24, 2018 09:30
-
-
Save ASPePeX/1e1323691395869bf1f8f63170dbad1f to your computer and use it in GitHub Desktop.
Casting Span<T> Example - int to byte and back
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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