Search code examples
c#arrayscopymemcpyunsafe

Copying values into a byte array at a specific offset in a safe context


I am trying to copy the value of a uint into a byte array in C#. I have managed to accomplish this using code in an unsafe context but ideally, I would like to do this in a safe context

The code I am currently using is this

var bytes = new byte[] {0x68, 0x00, 0x00, 0x00, 0x00}

fixed (byte* bytesPointer = bytes )
{
    *(ulong*)(bytesPointer + 1) = value;
}

The equivalent of what I am trying to accomplish in C# can be done like this in C++

unsigned char bytes[] = {0x68, 0x00, 0x00, 0x00, 0x00}

memcpy(((unsigned long)bytes + 1), value, 4);

How could I do this in a safe context in C#?


Solution

  • You could use these

    Array.Copy(Array, Int32, Array, Int32, Int32)

    Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers.

    Buffer.BlockCopy(Array, Int32, Array, Int32, Int32) Method

    Copies a specified number of bytes from a source array starting at a particular offset to a destination array starting at a particular offset.