簡體   English   中英

將uint復制到字節數組並在字節數組(和后面)內進行比較的最快方法

[英]Fastest way to copy a uint to a byte array and to compare it inside a byte array (and back)

我需要經常做以下事情(這里可以忽略endianness,我只使用x86):

  1. 將給定的uint與字節數組中的特定偏移量進行比較(也許我可以一次比較所有4個字節?)
  2. 從具有偏移量的字節數組復制4個字節到uint
  3. 將uint復制到字節數組中的特定偏移量(它將覆蓋此數組中的4個字節)
  4. 將12個字節復制到結構:( uint,uint,byte,byte,byte,byte)

最后一個不經常使用。 但如果我能用一些不安全的操作來做這件事就會非常有趣。

最快的方法是什么? 第一個是最重要的,因為我做的最多,並且使用最多的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個字節。

將uint復制到字節數組中的特定偏移量

  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);
  } 

統計(1 000 000電話)

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM