【问题标题】:C# send hex string as hexC#将十六进制字符串作为十六进制发送
【发布时间】:2019-02-21 07:22:52
【问题描述】:

我有一个字符串,我想将它作为十六进制值而不是 ascii 值发送

我的字符串是:

0x5C 0x21 0x5C

但是当我发送它时,我发送:

30-78-35-43-20-30-78-32-31-20-30-78-35-43

我怎么能克服这个?

我错过了什么?

这是完整的代码:

         byte[] address = { 0x30, 0x35 };
          byte[] end = { 0x03 };

        string Start = "0x5C 0x21 0x5C 0x73 0x20 0x73";
        for (int x = 0; x < msg.Count; x++)

        Console.WriteLine(Start);



        byte[] ByteMessage = encoding.GetBytes(Start);

        string HexMessage = BitConverter.ToString(ByteMessage);

        var temp = new MemoryStream();
        temp.Write(address, 0, address.Length);
        temp.Write(ByteMessage, 0, ByteMessage.Length);
        temp.Write(end, 0, end.Length);

        byte[] testing = temp.ToArray();
        var lrs = gen(testing);
        string lrsString = lrs.ToString("X");



        Console.WriteLine("MSG in HEX -  " + HexMessage);

        Console.Write(
                      Encoding.Default.GetString(address) +

                      encoding.GetString(ByteMessage) +

                      Encoding.Default.GetString(end) +

                      );



        byte[] LRS = Encoding.Default.GetBytes(lrsString);

        try
        {

            sp1.Write(start, 0, start.Length); //send start 
            sp1.Write(testing, 0, testing.Length);//send the all msg 
            sp1.Write(LRS, 0, LRS.Length);//send the Check Sum 
        }

        catch (Exception e)
        {
            Console.WriteLine(e);

        }

        finally
        {

        }

谢谢,

【问题讨论】:

  • 您再次将十六进制字符串编码为十六进制。
  • 你是怎么得到string Start = "0x5C 0x21 0x5C";的?
  • 我需要这样做,这样我才能使用 byte[] 发送它,不是吗?看看我的帖子 - 我已经添加了更多,谢谢,
  • 你为什么不首先使用byte[] ByteMessage = new byte[] {0x5C, 0x21, 0x5C, 0x73, 0x20, 0x73};
  • 这是我需要使用的字符串示例

标签: c# character-encoding hex


【解决方案1】:

您可能正在寻找解析(每个string 项目,如"0x5C" 应解析为相应的byte0x5C):

string Start = "0x5C 0x21 0x5C";

byte[] ByteMessage = Start
  .Split(' ')                               // Split string into items
  .Select(item => Convert.ToByte(item, 16)) // Parse items into corresponding bytes
  .ToArray();                               // Materialize into array

// Back to Hex (let's have a look on what we are going to send): "5C-21-5C"
string HexMessage = string.Join("-", ByteMessage
  .Select(item => item.ToString("X2")));

【讨论】:

  • 再见——如果我的字符串没有 "0x" ,会不会简单得多?因为我在字符串中添加了“0x”...
  • @David12123: Convert.ToByte(item, 16) 足够聪明,可以处理或不处理0x 前缀;这就是为什么string Start = "5C 21 5C"; 会被正确解析的原因。您不必添加"0x"
  • 太棒了! ,所以我将使用没有“0x”的字符串=非常感谢您的帮助!
猜你喜欢
  • 2018-01-31
  • 2018-01-22
  • 2017-08-12
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 2011-08-04
  • 2020-11-07
相关资源
最近更新 更多