【发布时间】:2011-09-07 01:36:23
【问题描述】:
我找到了一个源代码并对其进行了一些更改,以便我可以从 com6 上的接收器检索数据。我收到的数据是二进制的。现在我想将其转换为十六进制字符串。如果它是一个十六进制字符串,我们可以剪切部分字符串并单独解码。我该怎么做?
以下是代码:
using System;
using System.IO.Ports;
using System.Threading;
public class PortChat
{
static bool _continue;
static SerialPort _serialPort;
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = SetPortName(_serialPort.PortName);
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity = SetPortParity(_serialPort.Parity);
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);
// Set the read/write timeouts
_serialPort.ReadTimeout = 1000;
_serialPort.WriteTimeout = 1000;
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
catch (TimeoutException) { }
}
}
public static string SetPortName(string defaultPortName)
{
string portName;
portName = "COM6";
return portName;
}
public static int SetPortBaudRate(int defaultPortBaudRate)
{
string baudRate;
baudRate = "9600";
return int.Parse(baudRate);
}
public static Parity SetPortParity(Parity defaultPortParity)
{
string parity;
parity = "None";
return (Parity)Enum.Parse(typeof(Parity), parity);
}
public static int SetPortDataBits(int defaultPortDataBits)
{
string dataBits;
dataBits = "8";
return int.Parse(dataBits);
}
public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
{
string stopBits;
stopBits = "One";
return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
}
public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
{
string handshake;
handshake = "None";
return (Handshake)Enum.Parse(typeof(Handshake), handshake);
}
}
【问题讨论】:
-
你为什么转发?您只会编辑该帖子。显示您的接收方式以及您希望如何将其转换为??
-
只是让你知道。您收到的所有数据都是二进制的。这就是为什么在不理解代码的情况下使用代码是一个坏主意。
-
当我使用 _SerialPort.ReadLine() 然后使用 console.write 时,我得到一个随机字符和没有意义的符号的屏幕。我想要的是将二进制数据包转换为十六进制字符串,然后对其进行操作。