Search code examples
c#intbyteunsafestackalloc

How to set an int to byte* C#


How can I convert an int to a byte* at a certain index in a byte*?

Ideally I would like to have something like:

unsafe{
    byte* igm=stackalloc byte[8];
    igm[4]=4283;
}

It would set the first part of the bit to igm[4] and the rest into igm[5].

Edit: I realize there may be a lot of possible ways to handle this, i am looking for the most efficient way if possible.


Solution

  • try this:

    unsafe
    {
        byte* igm = stackalloc byte[8];
        *(int*)(igm + 4) = 4283;
    }
    

    Once you realize that you can use simple pointer arithmetic to index anywhere in your byte array, things get a LOT easier.