Search code examples
c#arrayspointersunsafe

C# - Fastest way to convert an int and put it in a byte array with an offset


I'm writing custom byte stream and I want the most the write/read methods that works the fastest way possible. This is my current implementation of the write and read methods for int32:

    public void write(int value)
    {
        unchecked
        {
            bytes[index++] = (byte)(value);
            bytes[index++] = (byte)(value >> 8);
            bytes[index++] = (byte)(value >> 16);
            bytes[index++] = (byte)(value >> 24);
        }
    }

    public int readInt()
    {
        unchecked
        {
            return bytes[index++] |
                (bytes[index++] << 8) |
                (bytes[index++] << 16) |
                (bytes[index++] << 24);
        }
    }

But what I really want is to do is cast the "int" into a byte pointer (or something like that) and copy the memory into the "bytes" array with the given "index" as the offset. Is it even possible in C#?

The goal is to:
Avoid creating new arrays.
Avoid loops.
Avoid multiple assignment of the "index" variable.
Reduce the number of instructions.


Solution

  • unsafe
    {
        fixed (byte* pbytes = &bytes[index])
        {
            *(int*)pbytes = value;
            value = *(int*)pbytes;
        }
    }
    

    But be careful with possible array index overflow.