我正在尝试将 ushort 放入 ArraySegment
public unsafe static void SetUshort(in ushort value, in int i1, in int i2, in ArraySegment<byte> arr)
{
var b = (byte)((value >> 8) & 255); // Exception line
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));
}
使用 ushort.MinValue 的测试用例通过。
我根本不知道你为什么要使用
&
。
我们真的只想右移 8 位。
这应该足够了并且可以按预期工作。
byte b1 = (byte)(value >> 8);
byte b2 = (byte)value;