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

1.6k Views Asked by At

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.

2

There are 2 best solutions below

5
On BEST ANSWER
unsafe
{
    fixed (byte* pbytes = &bytes[index])
    {
        *(int*)pbytes = value;
        value = *(int*)pbytes;
    }
}

But be careful with possible array index overflow.

0
On

Your code is very fast, but you can speed it even more (almost 2x faster) with the following change:

bytes[index] = (byte)(value);
bytes[index+1] = (byte)(value >> 8);
bytes[index+2] = (byte)(value >> 16);
bytes[index+3] = (byte)(value >> 24);
index = index + 4;