[英]Convert list<int[]> to byte[]
How to convert list<int[]>
to byte[]
? 如何将list<int[]>
转换为byte[]
?
I could use this: 我可以用这个:
byte[] bytes = lista.SelectMany(BitConverter.GetBytes).ToArray();
But it works only for list<int>
. 但是它仅适用于list<int>
。 If you have few ideas - most efficient is welcome. 如果您有什么想法-最有效的方法就是欢迎。
How about this: 这个怎么样:
byte[] bytes =
lista
.SelectMany(x => x)
.SelectMany(BitConverter.GetBytes)
.ToArray();
UPDATE: 更新:
To convert the result to List<int>
, you can do the following: 要将结果转换为List<int>
,可以执行以下操作:
List<int> list =
bytes
.Select((item, index) => new {item, index})
.GroupBy(x => x.index/4)
.Select(g => g.Select(x => x.item).ToArray())
.Select(x => BitConverter.ToInt32(x, 0))
.ToList();
var listOfIntArray = new List<int[]>
{
new[] {1, 2, 3},
new[] {4, 5},
new[] {6}
};
var listOfBytes = new List<byte>();
foreach (var intArray in listOfIntArray)
{
var listOfByteArray = intArray.Select(BitConverter.GetBytes);
foreach (var byteArray in listOfByteArray)
{
listOfBytes.AddRange(byteArray);
}
}
If you used the BitConverter
on purpose you can use this (will output all 4 bytes of the integer separately) 如果您故意使用BitConverter
,则可以使用它(将分别输出整数的所有4个字节)
byte[] buffer = testData.SelectMany(arr => arr.SelectMany(x => BitConverter.GetBytes(x))).ToArray();
for the sake of completeness: 为了完整性:
List<int> reversed = Enumerable.Range(0, buffer.Length / 4)
.Select(x => BitConverter.ToInt32(buffer, x * 4))
.ToList();
As in Yacoub Massad's answer this will revers in a List<int>
instead of List<int[]>
because by flatten the List<int[]>
first we lose the length informationen of the arrays. 就像Yacoub Massad的回答一样,这将在List<int>
而不是List<int[]>
反转,因为首先通过平展List<int[]>
我们失去了数组的长度信息。
If you only want to cast the int values to bytes you can use this 如果只想将int值转换为字节,则可以使用此方法
byte[] buffer = testData.SelectMany(arr => arr.Select(x => (byte)x)).ToArray();
var result = lista.SelectMany(x => x.SelectMany(y => BitConverter.GetBytes(y))).ToArray();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
byte[] bytes = bos.toByteArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.