[英]Fastest way to copy a uint to a byte array and to compare it inside a byte array (and back)
我需要經常做以下事情(這里可以忽略endianness,我只使用x86):
最后一個不經常使用。 但如果我能用一些不安全的操作來做這件事就會非常有趣。
最快的方法是什么? 第一個是最重要的,因為我做的最多,並且使用最多的CPU時間。 可能存在不安全的代碼(如果速度更快)。
編輯:
Currenlty我使用這樣的東西將uint復制到一個字節數組中:
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];
}
對於反向轉換,我使用此:
BitConverter.ToUInt32(arr, offset)
最后一個是如此少的代碼,第一個是這么多,也許有優化。 為了比較,目前我將其轉換回來(第二個),然后我將uint與我想要比較的值進行比較:
BitConverter.ToUInt32(arr, offset) == myVal
對於第四部分(提取結構)我使用這樣的東西:
[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;
}
我認為使用不安全的代碼我應該能夠一次復制12個字節。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.