如何从 UInt128 类型中提取字节

How to extract bytes from the UInt128 type

PacketDotNet 库定义了一个结构 UInt128。参见:

如何在 C# 中将此类型转换为简单的字节数组?

看起来您将它分配给了一个 BigInteger 变量并在其上使用了 ToByteArray() 方法。

UInt128 n128 = 12345;
BigInteger bi = (BigInteger)n128;
byte[] ba = bi.ToByteArray();

它可以转换为 BigTnteger,然后调用 ToByteArray(),如下所示。

var number = new Uint128();

((BigInteger)number).ToByteArray();

我还发现了另一种可能性:

public static unsafe byte[] GetBytesFromUInt128(this UInt128 value)
{
    byte[] numArray = new byte[16];
    fixed (byte* numPtr = numArray)
        *(UInt128*) numPtr = value;
    return numArray;
}

您可以使用较新的 .net 核心执行的一些有趣的技巧:

var ui = UInt128.MaxValue - 1;

{
    var span = MemoryMarshal.Cast<UInt128, byte>(MemoryMarshal.CreateReadOnlySpan(ref ui, 1));

    for (int i = 0; i < UInt128.SizeOf; i++)
    {
        Console.WriteLine(span[i]);
    }
}

and/or 给出

[StructLayout(LayoutKind.Explicit)]
public struct UInt128Split
{
    [FieldOffset(0)]
    public UInt128 UInt128;

    [FieldOffset(0)]
    public ulong ULong1;

    [FieldOffset(1)]
    public ulong ULong2;

    [FieldOffset(0)]
    public uint UInt1;

    [FieldOffset(4)]
    public uint UInt2;

    [FieldOffset(8)]
    public uint UInt3;

    [FieldOffset(12)]
    public uint UInt4;

    [FieldOffset(0)]
    public byte Byte1;

    [FieldOffset(1)]
    public byte Byte2;

    [FieldOffset(2)]
    public byte Byte3;

    [FieldOffset(3)]
    public byte Byte4;

    [FieldOffset(4)]
    public byte Byte5;

    [FieldOffset(5)]
    public byte Byte6;

    [FieldOffset(6)]
    public byte Byte7;

    [FieldOffset(7)]
    public byte Byte8;

    [FieldOffset(8)]
    public byte Byte9;

    [FieldOffset(9)]
    public byte Byte10;

    [FieldOffset(10)]
    public byte Byte11;

    [FieldOffset(11)]
    public byte Byte12;

    [FieldOffset(12)]
    public byte Byte13;

    [FieldOffset(13)]
    public byte Byte14;

    [FieldOffset(14)]
    public byte Byte15;

    [FieldOffset(15)]
    public byte Byte16;
}

然后

var ui = UInt128.MaxValue - 1;

{
    ref UInt128Split rf = ref Unsafe.As<UInt128, UInt128Split>(ref ui);

    Console.WriteLine(rf.UInt1);
    Console.WriteLine(rf.UInt2);
    Console.WriteLine(rf.UInt3);
    Console.WriteLine(rf.UInt4);

    Console.WriteLine(rf.ULong1);
    Console.WriteLine(rf.ULong2);

    // rf is the same as ui, so if we modify rf we modify ui!
    Console.WriteLine(ui);
    rf.ULong1 -= 11454;
    Console.WriteLine(ui);
}