110,533
社区成员
发帖
与我相关
我的任务
分享
//假设我有一个已知的a
byte[] a = { 1,2,3,4,5,6,7,8,9 };
//规则是这样,每隔4个我要加“ 后面长度,0,0,0}
//目标是搞成 b
byte[] b = { 4, 0, 0, 0, 1, 2, 3, 4, 4, 0, 0, 0, 5, 6, 7, 8, 1, 0, 0, 0, 9 };
//我应该怎么弄。。。最好敲点代码提醒一下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
byte[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
byte[] result = a.Select((x, i) => new { x, i })
.GroupBy(x => x.i / 4)
.SelectMany(x => new byte[] { (byte)x.Count(), 0, 0, 0 }.Concat(x.Select(y => y.x)))
.ToArray();
Console.WriteLine(string.Join(", ", result.Select(x => x.ToString())));
}
}
}
4, 0, 0, 0, 1, 2, 3, 4, 4, 0, 0, 0, 5, 6, 7, 8, 1, 0, 0, 0, 9
请按任意键继续. . . byte[] getbytes(byte[] bytes)
{
try
{
var remainder = bytes.Count() % 4; //1
var divtime = bytes.Count() / 4; //2
if (remainder != 0)
{
var lstbytes = new List<byte[]>();
for (int i = 0; i < divtime; i++)
{
var bys = bytes.Skip(i * 4).Take(4).ToArray();
var b = new byte[] { 4, 0, 0, 0 };
lstbytes.Add(b);
lstbytes.Add(bys);
}
var tmpBytes = bytes.Skip(divtime * 4).Take(remainder).ToArray();
var otherbytes = new byte[] { (byte)tmpBytes.ToList().Count(), 0, 0, 0 };
lstbytes.Add(otherbytes);
lstbytes.Add(tmpBytes);
return lstbytes.SelectMany(P => P).ToArray();
}
else
{
var lstbytes = new List<byte[]>();
for (int i = 0; i < divtime; i++)
{
var tmpbys = bytes.Skip(i * 4).Take(4).ToArray();
var otherbytes = new byte[] { 4, 0, 0, 0 };
lstbytes.Add(otherbytes);
lstbytes.Add(tmpbys);
}
return lstbytes.SelectMany(P => P).ToArray();
}
}
catch (Exception ex)
{
return new byte[] { };
}
}
byte[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var targetbytes = getbytes(a);