在C#中将int []转换为byte []
问题描述:
我知道如何做到这一点:通过创建必要大小的字节数组,并使用for循环来转换int数组中的每个元素.
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.
我想知道是否有更快的方法,因为如果int
大于sbyte
,上述方法似乎会中断.
I was wondering if there was a faster way, as it seems that the method above would break if the int
was bigger than an sbyte
.
答
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);
请勿使用 Array.Copy
,因为它会尝试进行转换,而不仅仅是复制.有关更多信息,请参见MSDN页面上的注释.
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.