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.
If int is less than -128, we just add than number with 256 to convert into byte. If int ranges between 128 to 256 inclusive, that number will be deducted with 256. If the number is greater than 256, We will divide that number with 256 and take the reminder...
We split the input integer (5000) into each byte by using the >> operator. The second operand represents the lowest bit index for each byte in the array. To obtain the 8 least significant bits for each byte, we & the result with 0xFF .
All that Java guarantees is that an int is 32 bits (4 bytes), so that you can store integer numbers with values between -2^31 and 2^31 - 1 in it.
A byte* cast using unsafe code is by far the fastest:
unsafe static void Main(string[] args) { int i = 0x12345678; byte* pi = (byte*)&i; byte lsb = pi[0]; // etc.. }
That's what BitConverter does as well, this code avoids the cost of creating the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With