BitConverter.GetBytes in place

后端 未结 5 899
-上瘾入骨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:37

    It seems that you wish to avoid, for some reason, creating any temporary new arrays. And you also want to avoid unsafe code.

    You could pin the object and then copy to the array.

    public static void ToBytes(ulong value, byte[] array, int offset) 
    {
        GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned);
        try
        {
            Marshal.Copy(handle.AddrOfPinnedObject(), array, offset, 8);
        }
        finally
        {
            handle.Free();
        }
    }
    

提交回复
热议问题