将int列表转换为字节数组
我试图使用List.ConvertAll方法并失败。 我想要做的是将List
转换为byte[]
我赶紧走了这条路,但我需要找出ConvertAll方法……
List integers... internal byte[] GetBytes() { List bytes = new List(integers.Count * sizeof(byte)); foreach (Int32 integer in integers) bytes.AddRange(BitConverter.GetBytes(integer)); return bytes.ToArray(); }
由于您不希望byte[][]
其中每个整数映射到四个字节的数组,因此您无法调用ConvertAll
。 ( ConvertAll
无法执行一对多转换)
相反,您需要调用LINQ SelectMany
方法将GetBytes
每个字节数组展平为单个byte[]
:
integers.SelectMany(BitConverter.GetBytes).ToArray()
怎么样
var bytes = integers.Select(i => BitConverter.GetBytes(i)).ToArray();
完全未经测试的BTW,但似乎合理。
这应该实际上给你一个字节数组的数组……这可能是你需要的,也可能不是。 如果要将其折叠为单个数组,可以使用SelectMany
var bytes = integers.SelectMany(i => BitConverter.GetBytes(i)).ToArray();
ConvertAll方法存在缺陷,因为它期望从源到目标的映射为1:1。 将整数转换为字节时不是这样。 最好使用@SLaks在SelectMany扩展方法中建议的解决方案。
要使用ConvertAll方法,您可以执行以下操作…
假设你有一个真正的字节值的int列表,而你实际上并不想要构成int所需的字节,即byte[][]
:
public static class Utility { public static byte IntToByte(int i) { if(i < 0) return (byte)0; else if(i > 255) return (byte)255; else return System.Convert.ToByte(i); } }
… 转换 …
byte[] array = listOfInts.ConvertAll( new Converter(Utility.IntToByte) ).ToArray();
或者你可以使用匿名代表……
byte[] array = listOfInts.ConvertAll( new Converter( delegate(int i) { if(i < 0) return (byte)0; else if(i > 255) return (byte)255; else return System.Convert.ToByte(i); })).ToArray();