我有Windows上的TextBox,在那里我成功地从com-端口接收十六进制数据,但是它显示在一行中,但我需要在HexDumpFormat中显示它。
我现在得到的是:

在搜索之后,我找到了示例代码:快速肮脏的六角排土场。这似乎是我所需要的,TC说我们所需要的只是将他的函数粘贴到我的代码中,并在我们需要的地方调用这个函数,但是我不知道如何使它与我的代码一起工作?非常感谢。(我不能附加超过3个链接,因此你可以看到一个链接页,HexDump格式是什么样的。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
string rs;
byte re;
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) // Da
{
try
{
//rs = serialPort1.ReadByte();
//re = Convert.ToByte(serialPort1.ReadByte());
rs = serialPort1.ReadExisting();
System.Text.Encoding.ASCII.GetString(new[] { re });
this.Invoke(new EventHandler(type));
}
catch (System.TimeoutException) { }
}
void type(object s, EventArgs e) // receive data
{
textBox4.Text += rs;
}
}
}发布于 2017-02-10 07:58:10
我试过链接上的代码。这个简单的例子:
byte[] byte_array = new byte[5];
byte_array[0] = 0xAC;
byte_array[1] = 0x12;
byte_array[2] = 0xA0;
byte_array[3] = 0xC5;
byte_array[4] = 0x88;
Console.WriteLine(Utils.HexDump(byte_array, byte_array.Length));下列产出的结果:

重要的是,要指定从数组中打印多少字节为1行。
您需要将数据从SerialPort中获取到字节数组中。我建议尝试以下代码:
SerialPort serialPort1 = new SerialPort();
byte[] byte_array = new byte[1024];
int counter = 0;
while (serialPort1.BytesToRead > 0)
{
byte_array[counter] = (byte)serialPort1.ReadByte();
counter++;
}编辑
若要能够使用来自链接的代码,请向项目中添加一个新的类文件。然后复制粘贴代码到里面。确保*.cs类文件与Form1类位于同一个项目中。
编辑2:
如果您收到HEX数字作为字符串。您可以自己将其转换为字节数组,然后使用链接中的Utils类来显示它。下面是实现这一目标的一个小示例代码:
string rs = "0004"; // example from your code
byte[] byte_array = new byte[rs.Length/2]; // array is half as long as your string
int idx = 0; // count variable to index the string
int cnt = 0; // count variable to index the byte array
while (idx < rs.Length-1)
{
byte_array[cnt] = (byte)Convert.ToInt32(rs.Substring(idx, 2), 16);
idx += 2;
cnt++;
}然后,您可以像这样打印结果:
textBox4.Text += Utils.HexDump(byte_array, cnt) + Environment.NewLine; https://stackoverflow.com/questions/42149688
复制相似问题