Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to convert int to 4 bytes in C#

Tags:

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.

like image 225
MichaelT Avatar asked Jan 11 '12 22:01

MichaelT


People also ask

How do you convert int to bytes mathly?

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...

How do you divide bytes into integers?

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 .

Is int always 4 bytes in Java?

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.


1 Answers

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.

like image 117
Hans Passant Avatar answered Oct 31 '22 11:10

Hans Passant