在 C# 中将 int[] 转换为 byte[] [英] Converting an int[] to byte[] in C#

查看:69
本文介绍了在 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.

推荐答案

如果您想要按位复制,即从一个 int 中获取 4 个字节,则使用 Buffer.BlockCopy:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆