首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >(C#)如何使HexDump格式与TextBox一起工作?

(C#)如何使HexDump格式与TextBox一起工作?
EN

Stack Overflow用户
提问于 2017-02-10 00:50:33
回答 1查看 726关注 0票数 1

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

我现在得到的是:

在搜索之后,我找到了示例代码:快速肮脏的六角排土场。这似乎是我所需要的,TC说我们所需要的只是将他的函数粘贴到我的代码中,并在我们需要的地方调用这个函数,但是我不知道如何使它与我的代码一起工作?非常感谢。(我不能附加超过3个链接,因此你可以看到一个链接页,HexDump格式是什么样的。

代码语言:javascript
复制
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;
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-10 07:58:10

我试过链接上的代码。这个简单的例子:

代码语言:javascript
复制
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中获取到字节数组中。我建议尝试以下代码:

代码语言:javascript
复制
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类来显示它。下面是实现这一目标的一个小示例代码:

代码语言:javascript
复制
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++;
}

然后,您可以像这样打印结果:

代码语言:javascript
复制
textBox4.Text += Utils.HexDump(byte_array, cnt) + Environment.NewLine; 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42149688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档