I need to do the following things very often (endianness can be ignored here, I only use x86):
- compare a given uint to a specific offset in a byte array (maybe I can compare all 4 bytes at once?)
- copy 4 bytes from a byte array with offset to a uint
- copy a uint to a specific offset in a byte array (it will overwrite 4 bytes in this array)
- copy 12 bytes to a struct: (uint, uint, byte, byte,byte, byte)
The last one is not so often used. But it would be very interesting if I could do it with just some unsafe operations.
What is the fastest way to do it? The first is the most important as I do it the most and is uses the most CPU time. Unsafe code is possible (if it is faster).
EDIT:
Currenlty I am using something like this to copy an uint into a byte array:
public static void Copy(uint i, byte[] arr, int offset)
{
var v = BitConverter.GetBytes(i);
arr[offset] = v[0];
arr[offset + 1] = v[0 + 1];
arr[offset + 2] = v[0 + 2];
arr[offset + 3] = v[0 + 3];
}
For the back conversion I use this:
BitConverter.ToUInt32(arr, offset)
The last one is so less code, the first one so much, maybe there is optimization.
For comparison, currently I convert it back (the second one) and then I compare the uint with the value I want to compare:
BitConverter.ToUInt32(arr, offset) == myVal
For the fourth Part (extracting a struct) I am using something like this:
[StructLayout(LayoutKind.Explicit, Size = 12)]
public struct Bucket
{
[FieldOffset(0)]
public uint int1;
[FieldOffset(4)]
public uint int2;
[FieldOffset(8)]
public byte byte1;
[FieldOffset(9)]
public byte byte2;
[FieldOffset(10)]
public byte byte3;
[FieldOffset(11)]
public byte byte4;
}
public static Bucket ExtractValuesToStruct(byte[] arr, int offset)
{
var b = new Bucket();
b.int1 = BitConverter.ToUInt32(arr, offset);
b.int2 = BitConverter.ToUInt32(arr, offset + 4);
b.byte1 = arr[offset + 8];
b.byte2 = arr[offset + 9];
b.byte3 = arr[offset + 10];
b.byte4 = arr[offset + 11];
return b;
}
I think using unsafe code I should be able to copy the 12 bytes at once.
Copy a uint to a specific offset in a byte array
Statistic (1 000 000 calls)