I'm trying to understand the new C# type Span<T>
When reading the Microsoft's article All About Span: Exploring a New .NET Mainstay I saw at the bottom of the What Is Span<T>?
section
Spans provide a multitude of benefits beyond those already mentioned. For example, spans support the notion of reinterpret casts, meaning you can cast a
Span<byte>
to be aSpan<int>
(where the 0th index into theSpan<int>
maps to the first four bytes of theSpan<byte>
). That way if you read a buffer of bytes, you can pass it off to methods that operate on grouped bytes as ints safely and efficiently.
They don't provide any example in this article but I eventually found the (new way) of doing this in Adam Storr's article by using the MemoryMarshal.Cast
method
However when I try to do this, I get a weird result
var byteArray = new byte[] { 1,0,0,0, 0,1,0,0};
Span<byte> byteSpan = byteArray;
Span<int> intSpan = MemoryMarshal.Cast<byte, int>(byteSpan);
Microsoft's articles says the 0th index into the Span maps to the first four bytes of the Span
. So by creating an array of 8 bytes I get a Span of 2 integers.
The value of the first integer is 1
which is what I was expecting (0001
) but the for 2nd integer I get the value 256
which is what I don't understand.
Am I not supposed to get the value 2
because the 2nd half of my bytes array is 0010
?
The number:
1
(which can be written in hex as):
0x00000001
0x0001
0x01
Has the big-endian byte pattern:
0x00 0x00 0x00 0x01
And the little-endian byte pattern:
0x01 0x00 0x00 0x00
The number:
256
(which can be written in hex as):
0x00000100
0x0100
Has the big-endian byte pattern:
0x00 0x00 0x01 0x00
And the little-endian byte pattern:
0x00 0x01 0x00 0x00
Since your machine is little-endian, the MemoryMarshal.Cast
is using the little-endian representations of numbers. Therefore 1 0 0 0
gets interpreted as 1
, and 0 1 0 0
gets interpreted as 256
.
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