What is a fastest way to convert int to 4 bytes in C# ?
Fastest as in execution time not development time.
My own solution is this code:
byte[] bytes = new byte[4];
unchecked
{
bytes[0] = (byte)(data >> 24);
bytes[1] = (byte)(data >> 16);
bytes[2] = (byte)(data >> 8);
bytes[3] = (byte)(data);
}
Right now I see that my solution outperforms both struct and BitConverter by couple of ticks.
I think the unsafe is probably the fastest option and accept that as an answer but I would prefer to use a managed option.
A byte* cast using unsafe code is by far the fastest:
That’s what BitConverter does as well, this code avoids the cost of creating the array.