加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将字节10替换为10 10

发布时间:2020-12-15 23:27:14 所属栏目:百科 来源:网络整理
导读:嗨我想替换一个字节[],其中有10乘10 10.这是我的代码. 如果我有我的数据为“10 20 10 20 40 50 50 50 50 10 03”我想重复它 “10 20 10 10 20 40 50 50 50 50 10 10 03” 注意:第一个字节不受影响 请按照我的评论,我的想法是将字节数组推到nxt位置并添加另
嗨我想替换一个字节[],其中有10乘10 10.这是我的代码.
如果我有我的数据为“10 20 10 20 40 50 50 50 50 10 03”我想重复它
“10 20 10 10 20 40 50 50 50 50 10 10 03”
注意:第一个字节不受影响
请按照我的评论,我的想法是将字节数组推到nxt位置并添加另外10个.

foreach (var b in command.ToBytes()) 
                {

                   // var c = b;
                    transmitBuffer[count++] = b;  data is formed here
                    addedbuffer[addall++] = b;     duplication is made
                }
                if (addedbuffer[0] == 16 && addedbuffer[1] == 32 || addedbuffer[50] == 16 && addedbuffer[51] == 03)           /
                    {
/condition on which to enter here
                        addedbuffer[0] = 0;  //making 1st and 2nd value as null
                        addedbuffer[1] = 0;
                        for (int i = 0; i < addedbuffer.Length; i++) //till length i will chk 
                        {
                            if (addedbuffer[i] == 10) //replace 10  by 10 10 
                                addedbuffer[i] = 1010; // error,}




        }

解决方法

你不能插入数组(你可以使用List< T>),所以看起来你必须创建一个新的数组; Linq解决方案:

Byte[] source = new Byte[] {
    20,10,20,40,50,03
  };

  var result = source
    .SelectMany((item,index) => 
       item == 10 && index != 0 ? new Byte[] { item,item } : new Byte[] { item })
    .ToArray();

但是,使用List< Byte> (为了只插入10个)而不是Byte []是一个更好的出路:

List<Byte> list = List<Byte>() {
    20,03
  };

  // In order not to read inserted 10's we loop backward 
  // i >= 1: 1st byte should be preserved as is even if its == 10
  for (int i = list.Count - 1; i >= 1; --i)
    if (list[i] == 10)
      list.Insert(i + 1,10);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读