简体   繁体   中英

C# byte operations optimization: how to get dword from byte[] array

Is it possible to get 4 bytes from byte[] array in one operation ?

That means instead of:

var octet_a = bytes[i++];
var octet_b = bytes[i++];
var octet_c = bytes[i++];
var octet_d = bytes[i++];

get something like

Int32 b4= Get4Bytes(i);
i=i+4;

You can use BitConverter. as it actually uses unsafe approach to convert byte array to number if possible.

var dword = BitConverter.ToInt32(bytes, i);

This will be optimized by jitter once it executes first time. if you try similar approaches yourself you wouldn't get much better performance.

As mentioned, you can use BitConverter which will definitely do this much better than you can, but in case you still want to know how it's done:

public unsafe int Get4Bytes(byte[] bytes, int index)
{
    fixed (byte* b = &bytes[index])
    {
        var v = (int*)b;
        return *v;
    }
}

First we get a pointer to the index byte b using fixed . Since C# is a managed language, the runtime can move memory around whenever it feels like it. We use fixed to tell the runtime not to move bytes while we're doing unsafe operations against the memory.

Once inside fixed, b is currently a byte* (a pointer to a byte), but you want 4 bytes, so we cast it to a int* (pointer to an int). Note that it's still the same value. Then we de-reference the pointer to get the actual integer value. ( *v )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM