Reputation: 4485
I need to do the following things very often (endianness can be ignored here, I only use x86):
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.
Upvotes: 3
Views: 3030
Reputation: 16981
unsafe public static void UnsafeCopy(uint i, byte[] arr, int offset)
{
fixed (byte* p = arr)
{
*((uint*)(p + offset)) = i;
}
}
public static void ShiftCopy(uint i, byte[] arr, int offset)
{
arr[offset] = (byte)(i & 0xFF);
arr[offset + 1] = (byte)((i >> 8) & 0xFF);
arr[offset + 2] = (byte)((i >> 16) & 0xFF);
arr[offset + 3] = (byte)((i >> 24) & 0xFF);
}
00:00:00.0414024: copy. get bytes
00:00:00.0136741: unsafe copy
00:00:00.0154764: shift copy
Upvotes: 5