Converting an int[] to byte[] in C#

前端 未结 3 1696
粉色の甜心
粉色の甜心 2020-12-02 12:33

I know how to do this the long way: by creating a byte array of the necessary size and using a for-loop to cast every element from the int array.

I was wondering i

相关标签:
3条回答
  • 2020-12-02 12:43
    int[] ints = { 1, 2, 3, 4, 5, 6 };
    byte[] bytes = ints.Select(x => (byte)x).ToArray();
    
    0 讨论(0)
  • 2020-12-02 12:52

    Besides the accepted answer (which I am now using), an alternative one-liner for Linq lovers would be:

    byte[] bytes = ints.SelectMany(BitConverter.GetBytes).ToArray(); 
    

    I suppose, though, that it would be slower...

    0 讨论(0)
  • 2020-12-02 13:00

    If you want a bitwise copy, i.e. get 4 bytes out of one int, then use Buffer.BlockCopy:

    byte[] result = new byte[intArray.Length * sizeof(int)];
    Buffer.BlockCopy(intArray, 0, result, 0, result.Length);
    

    Don't use Array.Copy, because it will try to convert and not just copy. See the remarks on the MSDN page for more info.

    0 讨论(0)
提交回复
热议问题