在C#中将int []转换为byte [] [英] Converting an int[] to byte[] in C#
本文介绍了在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.
这篇关于在C#中将int []转换为byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文