将 4 个整数打包到 ulong 中的更好方法是什么?

What is a better way to pack 4 ints into ulong?

我需要将几个int值(每个值的范围从0到999)打包到ulong中。我有一个像下面这样的工作方法,但它可以优化吗?

我知道很多 0 会伤害您的眼睛,抱歉。

public class Test  {

    public void Start() {
        ulong testValue = 444333222111;

        Debug.Log(GetValue1(testValue) + " " + GetValue2(testValue) + " " + GetValue3(testValue) + " " + GetValue4(testValue)); // = 111 222 333 444

        SetValue1(ref testValue, 55);
        SetValue2(ref testValue, 9);
        SetValue3(ref testValue, 111);
        SetValue4(ref testValue, 999);

        Debug.Log(testValue); // = 999111009055
        Debug.Log(GetValue1(testValue) + " " + GetValue2(testValue) + " " + GetValue3(testValue) + " " + GetValue4(testValue)); // = 55 9 111 999
    }

    public int GetValue1(ulong i) => (int)(i % 1000);
    public void SetValue1(ref ulong i, int value) => i = i / 1000 * 1000 + (ulong)value;

    public int GetValue2(ulong i) => (int)(i % 1000000 / 1000);
    public void SetValue2(ref ulong i, int value) => i = i / 1000000 * 1000000 + (ulong)value * 1000 + i % 1000;

    public int GetValue3(ulong i) => (int)(i % 1000000000 / 1000000);
    public void SetValue3(ref ulong i, int value) => i = i / 1000000000 * 1000000000 + (ulong)value * 1000000 + i % 1000000;

    public int GetValue4(ulong i) => (int)(i % 1000000000000 / 1000000000);
    public void SetValue4(ref ulong i, int value) => i = i / 1000000000000 * 1000000000000 + (ulong)value * 1000000000 + i % 1000000000;

}

给你。首先创建一个 [StructLayout(LayoutKind.Explicit)] 结构,如:

[StructLayout(LayoutKind.Explicit)]
public struct FourWords
{
    [FieldOffset(0)] public ulong Whole;
    [FieldOffset(0)] public ushort First;
    [FieldOffset(2)] public ushort Second;
    [FieldOffset(4)] public ushort Third;
    [FieldOffset(6)] public ushort Fourth;
}

然后您可以像您期望的那样访问第一个、第二个...字段中的每一个:

 FourWords test = new FourWords();
 test.Second = 0x101;
 test.Fourth = 0xA0A;
 var xyz = test.Whole;

如果您在调试器中查看 xyz(十六进制视图),您会看到:

    xyz, h  0x0a0a000001010000  ulong

你可以看到 101 和 A0A。