BitConverter.GetBytes in place

后端 未结 5 866
-上瘾入骨i
-上瘾入骨i 2021-01-20 05:17

I need to get values in UInt16 and UInt64 as Byte[]. At the moment I am using BitConverter.GetBytes, but this method give

5条回答
  •  一整个雨季
    2021-01-20 05:48

    You say you want to avoid creating new arrays and you cannot use unsafe. Either use Ulugbek Umirov's answer with cached arrays (be careful with threading issues) or:

    static void ToBytes(ulong value, byte[] array, int offset) {
     unchecked {
      array[offset + 0] = (byte)(value >> (8*7));
      array[offset + 1] = (byte)(value >> (8*6));
      array[offset + 2] = (byte)(value >> (8*5));
      array[offset + 3] = (byte)(value >> (8*4));
      //...
     }
    }
    

提交回复
热议问题