位移位导致 System.OverflowException :算术运算导致溢出

问题描述 投票:0回答:1

我正在尝试将 ushort 放入 ArraySegment,但由于此异常,我无法获取 ushort 的第二个字节。注释部分有效,但我想使用索引,因为我发现它更简单。

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 的测试用例通过。

c#
1个回答
0
投票

我根本不知道你为什么要使用

&
。 我们真的只想右移 8 位。

这应该足够了并且可以按预期工作。

byte b1 = (byte)(value >> 8); 
byte b2 = (byte)value;
© www.soinside.com 2019 - 2024. All rights reserved.