将int列表转换为字节数组

时间:2010-06-22 23:12:00

标签: c# list convertall

我尝试使用List.ConvertAll方法但失败了。我要做的是将List<Int32>转换为byte[]

我赶紧走了这条路,但我需要找出ConvertAll方法......

List<Int32> integers...

internal byte[] GetBytes()
{
    List<byte> bytes = new List<byte>(integers.Count * sizeof(byte));
    foreach (Int32 integer in integers)
        bytes.AddRange(BitConverter.GetBytes(integer));

    return bytes.ToArray();
}

4 个答案:

答案 0 :(得分:16)

由于您不希望byte[][]每个整数映射到四个字节的数组,因此您无法调用ConvertAll。 (ConvertAll无法执行一对多转换)

相反,您需要调用LINQ SelectMany方法将每个字节数组从GetBytes展平为单个byte[]

integers.SelectMany(BitConverter.GetBytes).ToArray()

答案 1 :(得分:3)

怎么样

var bytes = integers.Select(i => BitConverter.GetBytes(i)).ToArray();

完全未经测试的BTW,但似乎是合理的。

这实际上应该为您提供一个字节数组数组......这可能是您需要的也可能不是。如果要将其折叠为单个数组,可以使用SelectMany

var bytes = integers.SelectMany(i => BitConverter.GetBytes(i)).ToArray();

答案 2 :(得分:2)

ConvertAll方法存在缺陷,因为它期望从源到目标的映射为1:1。将整数转换为字节时不是这样。使用@SLaks在SelectMany扩展方法中建议的解决方案,你会好得多。

答案 3 :(得分:1)

要使用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<byte, int>(Utility.IntToByte) ).ToArray();

或者你可以使用匿名代表......

byte[] array = listOfInts.ConvertAll( new Converter<byte, int>(
                   delegate(int i) {
                       if(i < 0)
                          return (byte)0;
                       else if(i > 255)
                          return (byte)255;
                       else
                          return System.Convert.ToByte(i);
                   })).ToArray();