Best way to copy a bit in terms of performance, in C #

What is the fastest way to copy bitfrom Intto byte array, in C # ?

I have a couple Int, and I need to copy (sometimes all and several times some of) bitsequentially in byte[]...

I need the process to be as efficient as possible (for example, avoid creating a new one byte arrayin the process, as I understand it, BitConverterdoes, etc.).

+4
source share
1 answer

One way to avoid creating a new array byte[]for each call is to create it BinaryWriteron top MemoryStream, write integers to it, and then collect all the results at once by accessing the MemoryStreambuffer:

var buf = new byte[400];
using (var ms = new MemoryStream(buf))
using (var bw = new BinaryWriter(ms)) {
    for (int i = 0 ; i != 100 ; i++) {
        bw.Write(2*i+3);
    }
}
// At this point buf contains the bytes of 100 ints
+3
source

All Articles