In C #, convert ulong [64] to byte [512] faster?

I have a way to convert ulongs to bytes using binary shifts in a for statement, but this is not very efficient. Is there a way to pass a ulong array of size 64 directly to a byte array of size 512? This is a piece of code that runs thousands of times, and I need to save every millisecond so that I can, in turn, save seconds.

Edit: Now this is what I am doing:

  for (int k = 0; k < ulongs.Length; k++) { bytes[(k << 3)] = (byte)(ulongs[k] >> 56); bytes[(k << 3) + 1] = (byte)(ulongs[k] >> 48); bytes[(k << 3) + 2] = (byte)(ulongs[k] >> 40); bytes[(k << 3) + 3] = (byte)(ulongs[k] >> 32); bytes[(k << 3) + 4] = (byte)(ulongs[k] >> 24); bytes[(k << 3) + 5] = (byte)(ulongs[k] >> 16); bytes[(k << 3) + 6] = (byte)(ulongs[k] >> 8); bytes[(k << 3) + 7] = (byte)(ulongs[k]); } 
+4
source share
4 answers
 unsafe { fixed (ulong* src = ulongs) { Marshal.Copy(new IntPtr((void*)src), bytes, 0, 512); } } 

It seems to work. I'm not sure what is fixed, but I lost a whole second during time tests.

+4
source

Probably the fastest way to do this is to use unsafe and fixed constructs. Here is an example:

 ulong[] ulongs = new ulong[64]; byte[] bytes = new byte[512]; unsafe { fixed (ulong* src = ulongs) { byte* pb = (byte*)src; for (int i = 0; i < bytes.Count(); i++) { bytes[i] = *(pb + i); } } } 

Remember to use the /unsafe compiler when compiling the code above.

Edit: here is the version of the first code fragment that works on my machine much faster:

 unsafe { fixed (ulong* src = ulongs) { fixed (byte *dst = bytes) { ulong* pl = (ulong*)dst; for (int i = 0; i < ulongs.Count(); i++) { *(pl + i) = *(src + i); } } } } 
+3
source

You may be able to achieve this using struct and explicit layout statements, using the StructLayout attribute to force the variables to occupy the same space.

That way, you can write the value using the ulong property and read it using the byte array property. This assumes, of course, that the byte array does occupy the expected space and that it does not use 32 bits to store 8 bits of information. I have to look at this in a specification that I haven't done yet.

0
source

Use the System.Buffer helper class.

 ulong[] buffer = null; int byteLength = Buffer.ByteLength(buffer); byte[] byteBuffer = new byte[byteLength]; Buffer.BlockCopy(buffer, 0, byteBuffer, 0, byteLength); 
0
source

Source: https://habr.com/ru/post/1273720/


All Articles