转换整数的列表,以字节数组 [英] Converting a list of ints to a byte array

查看:185
本文介绍了转换整数的列表,以字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 List.ConvertAll 方法和失败。我所试图做的是转换列表<的Int32> 字节[]



我copped出来,走到这条路,但我需要找出方法ConvertAll ...

 列表与LT;&的Int32 GT;整数... 

内部字节[] GetBytes会()
{
名单,LT;字节>字节=新的List<位>(integers.Count *的sizeof(字节));
的foreach(在整数的Int32整数)
bytes.AddRange(BitConverter.GetBytes(整数));

返回bytes.ToArray();
}


解决方案

既然你不想一个字节[] [] ,其中每个整数映射到四个字节数组,你不能叫 ConvertAll 。 ( ConvertAll 无法执行一到多的转换)



相反,你需要调用LINQ 的SelectMany 方法从 GetBytes会每个字节数组压扁成一个单一的字节[]

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


I tried to use the List.ConvertAll method and failed. What I am trying to do is convert a List<Int32> to byte[]

I copped out and went this route, but I need to figure out the ConvertAll method...

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();
}

解决方案

Since you don't want a byte[][] where each integer maps to an array of four bytes, you cannot call ConvertAll. (ConvertAll cannot perform a one-to-many conversion)

Instead, you need to call the LINQ SelectMany method to flatten each byte array from GetBytes into a single byte[]:

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

这篇关于转换整数的列表,以字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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