leng125172
江户川妮可
2021-01-16 22:52

C# 大佬帮忙看一下怎么把这个代码优化精简一下

  • c#
int ZD = 1;
string commandY = "01 03 00 00 00 02 C4 0B";
string commandG = "T1 03 00 00 00 02 T2";

byte[] byteArray = System.Text.Encoding.Default.GetBytes(commandG);
string cm = commandG.Replace("T1", ZD.ToString("X2"));
cm = cm.Replace("T2", "");
cm = cm.Trim();
Console.WriteLine(cm);
string[] ssArray = cm.Split(' ');
byte[] bytList = new byte[ssArray.Length];
for (int i = 0; i < bytList.Length; i++)
{                //将十六进制的字符串转换成数值
bytList[i] = Convert.ToByte(ssArray[i], 16);
}    //返回字节数组
foreach (var s in bytList)
{                //将十六进制的字符串转换成数值
Console.WriteLine(s.ToString("X2"));
}
Console.WriteLine("增加CRC");
CRCHelp cRCHelp = new CRCHelp();
bytList = cRCHelp.GetModbusCrc16(bytList);
foreach (var s in bytList)
{                //将十六进制的字符串转换成数值
Console.WriteLine(s.ToString("X2"));
}


//commandG是命令的格式,格式为string
//T1 替换为16进制数字"X2"
//T2为CRC校验码
//最终输出为byte[]

有没有什么好的写法

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答