簡體   English   中英

將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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM