从端口C#二进制数据转换为十六进制字符串
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从端口C#二进制数据转换为十六进制字符串相关的知识,希望对你有一定的参考价值。
我找到了一个源代码并稍微改了一下,所以我可以从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);
}
}
答案
试试这个
string Data = "123";
string hex = "";
foreach (char c in Data)
{
hex += String.Format("{0:x2}", (byte)c);
}
hex包含你想要的字符串
另一答案
看看BitConverter.ToString()
方法
以上是关于从端口C#二进制数据转换为十六进制字符串的主要内容,如果未能解决你的问题,请参考以下文章
3. 从键盘上输入一个八进制数,利用指针将其转换为十进制数并输出 C语言 很急