如何从 UInt128 类型中提取字节

时间:2021-01-21 13:13:08

标签: c# packetdotnet

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

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

4 个答案:

答案 0 :(得分:2)

看起来您将其分配给 BigInteger 变量并对其使用 ToByteArray() 方法。

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

答案 1 :(得分:2)

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

var number = new Uint128();

((BigInteger)number).ToByteArray();

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

您可以使用较新的 .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]);
    }
}

和/或给予

[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);
}
相关问题