4

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#?

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68

1 Answers1

2

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.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • The question is how to copy a `uint` (or, presumably, its `byte` representation) into a `byte[]`. Can you demonstrate how these methods would be used to accomplish that? The answer, as written, only makes mention of array-to-array copies; I think it would helpful to show that how to get a `byte[]` from a `uint` as well. – Lance U. Matthews Sep 28 '18 at 01:46
  • A `uint` is 4 unsigned bytes. To access the bytes in a uint, you can either mask and shift, or you can do the C# equivalent of a C `union`. That involves creating a `struct` using `LayoutKind.Explicit` that overlays the uint with 4 bytes. You set the uint part of the struct and then read the bytes. – Flydog57 Sep 28 '18 at 01:49
  • @LostBoy are you sure this answered your question? – TheGeneral Sep 28 '18 at 01:50
  • @Saruman When I saw the title I thought it was a "How do I copy between `byte` arrays?" question, too, and it took me a few reads to understand it. I think you methods you listed can be used, you just need a call to [`BitConverter.GetBytes()`](https://learn.microsoft.com/dotnet/api/system.bitconverter.getbytes#System_BitConverter_GetBytes_System_UInt32_) as an intermediate step. I just thought that would make the answer more complete, is all. – Lance U. Matthews Sep 28 '18 at 01:52
  • Yeah as mentioned by @BACON I used BitConverter.GetBytes() to get the byte representation of the uint and then simply used Buffer.BlockCopy() to copy into the array –  Sep 28 '18 at 01:54
  • @LostBoy are ok, there other way to do it is use Flydog57 suggestion its probably a lot quicker, ill update the answer soon, im just at work in a phone meeting, trying to pretend im interested – TheGeneral Sep 28 '18 at 01:56