int数组以字节数组 [英] int array to byte array
问题描述
我知道如何做到这一点的很长的路要走(创造必要的大小的字节数组,然后使用一个for循环和铸造从int数组的每一个元素),但不知道是否有一个更快的方法。
似乎是这样,如果INT是不是一个更大的为sbyte上面会打破。
I know how to do this the long way (create a byte array of the necessary size, then used a for loop and casting every element from the int array), but was wondering if there was a faster way. seems the way above would break if the int was bigger than an sbyte.
推荐答案
如果你想有一个逐位复制,即得到4个字节一颗颗为int,然后用<一个href=\"http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx\"><$c$c>Buffer.BlockCopy$c$c>:
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.
这篇关于int数组以字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!