首页 > 解决方案 > int[] 到 byte[] 的转换,1 个 int 对应 1 个字节

问题描述

我正在使用Stream.Write(byte[],int int)函数写入流,但我无法转换我的int[] to byte[],在我的整数数组中我有 56 个整数,它们都低于 8 位值。我想将我的 int [] byte[] 转换为我的 byte[] 也有 56 个字节。

像这样

int[]= {0x0004,0x0001,0x0003,0x0003}
字节[] ={ 0x04,0x01,0x03,0x03}

提前致谢

标签: c#type-conversionintbyte

解决方案


您必须从每个 int 中提取低字节:myByte = (byte)(myInt & 0xFF)

using System.Linq;
//...
int[] integers = {0x0004,0x0001,0x0003,0x0003};
byte[] bytes = integers.Select(n => (byte)(n & 0xFF)).ToArray();

推荐阅读