C#将十六进制字符串作为十六进制

问题描述 投票:0回答:1

我有一个字符串,我想发送它作为十六进制值而不是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
        {

        }

谢谢 ,

c# character-encoding hex
1个回答
3
投票

您可能正在寻找解析(每个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")));
© www.soinside.com 2019 - 2024. All rights reserved.