I am trying to get place a ushort into an ArraySegment<byte>, but I am unable to get the 2nd byte of the ushort due to this exception.
public unsafe static void SetUshort(in ushort value, in int i1, in int i2, in ArraySegment<byte> arr)
{
var b = (byte)((value >> 8) & 255);
arr[i1] = b;
arr[i2] = (byte)value;
//fixed (byte* p = arr.Array)
//{
// var ptr = p + arr.Offset;
// Buffer.MemoryCopy(&value, ptr, 2, 2);
//}
}
public static ushort GetUshort(int i1, int i2, ArraySegment<byte> arr)
{
return (ushort)(arr[i1] << 8 | arr[i2]);
}
[Test]
[TestCase(ushort.MinValue, 0, 1)]
[TestCase((ushort)5614, 0, 1)]
[TestCase(ushort.MaxValue, 0, 1)]
public void SetUshort_Correct(ushort testValue, int index1, int index2)
{
Helper.SetUshort(testValue, index1, index2, Body);
Assert.That(Helper.GetUshort(index1, index2, Body), Is.EqualTo(testValue));
}
I’ve tried to use pointers, which works.