BitConverter.GetBytes in place

后端 未结 5 867
-上瘾入骨i
-上瘾入骨i 2021-01-20 05:17

I need to get values in UInt16 and UInt64 as Byte[]. At the moment I am using BitConverter.GetBytes, but this method give

5条回答
  •  醉话见心
    2021-01-20 05:47

    You can do like this:

    static unsafe void ToBytes(ulong value, byte[] array, int offset)
    {
        fixed (byte* ptr = &array[offset])
            *(ulong*)ptr = value;
    }
    

    Usage:

    byte[] array = new byte[9];
    ToBytes(0x1122334455667788, array, 1);
    

    You can set offset only in bytes.

    If you want managed way to do it:

    static void ToBytes(ulong value, byte[] array, int offset)
    {
        byte[] valueBytes = BitConverter.GetBytes(value);
        Array.Copy(valueBytes, 0, array, offset, valueBytes.Length);
    }
    

    Or you can fill values by yourself:

    static void ToBytes(ulong value, byte[] array, int offset)
    {
        for (int i = 0; i < 8; i++)
        {
            array[offset + i] = (byte)value;
            value >>= 8;
        }
    }
    

提交回复
热议问题