我正在开发一个C#程序,该程序将使用三菱通信协议与变频器通信。
我正在准备几种方法来创建要发送的字节数组。
现在,我已经输入了更多的暴力方法来准备和发送字节。
public void A(Int16 Instruction, byte WAIT, Int32 Data )
{
byte[] A_Bytes = new byte[13];
A_Bytes[0] = C_ENQ;
A_Bytes[1] = 0x00;
A_Bytes[2] = 0x00;
A_Bytes[3] = BitConverter.GetBytes(Instruction)[0];
A_Bytes[4] = BitConverter.GetBytes(Instruction)[1];
A_Bytes[5] = WAIT;
A_Bytes[6] = BitConverter.GetBytes(Data)[0];
A_Bytes[7] = BitConverter.GetBytes(Data)[1];
A_Bytes[8] = BitConverter.GetBytes(Data)[2];
A_Bytes[9] = BitConverter.GetBytes(Data)[3];
Int16 SUM = 0;
for(int i = 0; i<10; i++)
{
SUM += A_Bytes[i];
}
A_Bytes[10] = BitConverter.GetBytes(SUM)[0];
A_Bytes[11] = BitConverter.GetBytes(SUM)[1];
A_Bytes[12] = C_CR;
itsPort.Write(A_Bytes, 0, 13);
}然而,这似乎是非常低效的。尤其是我经常调用GetBytes()这一事实。
这是一个好方法,还是有一个更短/更快的方法?
主要更新:
事实证明,三菱的结构在如何做到这一切方面有点不可靠。
它不是使用字节,而是使用ascii字符。因此,当ENQ仍然是0x05时,例如E1的指令代码实际上是0x45和0x31。
这实际上可能会让事情变得更容易。
发布于 2015-04-27 05:42:57
即使不改变你的算法,这也可以变得更有效率,更像C#。如果你对连接两个数组感到困扰,这当然是可选的。
var instructionBytes = BitConverter.GetBytes(instruction);
var dataBytes = BitConverter.GetBytes(data);
var contentBytes = new byte[] {
C_ENQ, 0x00, 0x00, instructionBytes[0], instructionBytes[1], wait,
dataBytes[0], dataBytes[1], dataBytes[2], dataBytes[3]
};
short sum = 0;
foreach(var byteValue in contentBytes)
{
sum += byteValue;
}
var sumBytes = BitConverter.GetBytes(sum);
var messageBytes = contentBytes.Concat(new byte[] { sumBytes[0], sumBytes[1], C_CR } );
itsPort.Write(messageBytes, 0, messageBytes.Length);但是,如果您发现自己编写了大量这样的代码,我建议您考虑将其包装到一个Message类中。这段代码将构成构造函数的基础。然后,您可以通过继承(或组合)来改变行为(使内容更长、更短等),并将消息作为对象而不是字节数组来处理。
顺便说一句,您可能会看到使用BinaryWriter而不是BitConverter带来的利润率提高(也许?),但使用它会更麻烦。(byte)(sum >> 8)也是另一个选择,我认为它实际上是最快的,而且在你的用例中可能是最有意义的。
https://stackoverflow.com/questions/29883606
复制相似问题