编码字符串以获取“0x0d”

Encoding string to Get "0x0d”

如何Encoding.ASCII.GetBytes(str)获取“0x0d”?

var hl7 = @"MSH|^~\&|||||20170718110131||DSR^Q03|1|P|2.3.1|||P|||ASCII|||@MSA|AA|1|Message accepted|||0|@ERR|0|@QAK|SR|OK|@QRD|20170718110131|R|D|2|||RD||OTH|||T|@QRF||||||RCT|COR|ALL||@DSP|1||1212|||@DSP|2||27|||@DSP|3||Tommy|||@DSP|4||19620824000000|||@DSP|5||M|||@DSP|6||O|||@DSP|7|||||@DSP|8|||||@DSP|9|||||@DSP|10|||||@DSP|11|||||@DSP|12|||||@DSP|13|||||@DSP|14|||||@DSP|15||outpatient|||@DSP|16|||||@DSP|17||own|||@DSP|18|||||@DSP|19|||||@DSP|20|||||@DSP|21||0019|||@DSP|22||3|||@DSP|23||20170718120500|||@DSP|24||N|||@DSP|25||1|||@DSP|26||serum|||@DSP|27|||||@DSP|28|||||@DSP|29||1^^^|||@DSP|30||2^^^|||@DSP|31||5^^^|||@DSC||@";
byte[] msg;
int len = Encoding.ASCII.GetByteCount(hl7);
len += 3;
msg = new byte[len];
msg[0] = 0x0b;
Encoding.ASCII.GetBytes(hl7).CopyTo(msg, 1);
new byte[] { 0x1c, 0x0d }.CopyTo(msg, len - 2);
for (var i = 0; i < msg.Length; i++)
{
     if (msg[i] == 64)
     {
          msg[i] = 0x0d;
     }
}
tcpServer.Send(client, msg);

我向化学分析仪发送了 DSR^Q03 消息,这是我发送的消息。问题解决了,但我想得到更好的解决方案。

据我所知,您想对给定的命令进行编码

   string hl7 = @"MSH|^~\&|||...|@DSC||@";

转换成格式

   header = [0x0b]
   body   = Encoding.ASCII.GetBytes(hl7); each 64 shall be changed into 0x0d
   tail   = [0x1c, 0x0d]

同时将正文中的每个64变为0x0d。您可以尝试使用 Linq

   using System.Linq;

   ... 

   string hl7 = @"MSH|^~\&|||...|@DSC||@";

   byte[] msg = (new byte[] { 0x0b })
    .Concat(Encoding.ASCII.GetBytes(hl7).Select(b => b != 64 ? b : (byte)0x0d))
    .Concat(new byte[] { 0x1c, 0x0d })
    .ToArray();

   tcpServer.Send(client, msg);