如何根据此代码将Hex转换为ASCII?

时间:2016-05-15 10:33:15

标签: c# hex ascii

主要问题是How to display weight from weighing scale into a textbox via serial port RS-232 or usb converter?

现在我想获取hex的值并将其转换为ascii并显示。

主要代码是这个

public partial class MainForm : Form
{
    private SerialPort _serialPort; // formda kullanilacak degisken
    private const int BaudRate = 9600; // BaudRate Constant. default 9600 ile oynanabilir 
    public MainForm()
    {
        InitializeComponent();
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
        this.MinimizeBox = false;
        string[] portNames = SerialPort.GetPortNames(); // bütün kullanilabilecek com portlari okur
        foreach (var portName in portNames)
        {
            comboBox1.Items.Add(portName); // Adds Ports to combobox
        }
        if (comboBox1.SelectedIndex != -1)
        {
            comboBox1.SelectedIndex = 0; // Selects first entry (convenience purposes)
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // This block ensures that no exceptions happen
        if (_serialPort != null && _serialPort.IsOpen)
            _serialPort.Close();
        if (_serialPort != null)
            _serialPort.Dispose();
        // End of Block

        _serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One);  //<-- Creates new SerialPort using the name selected in the combobox

        _serialPort.DataReceived += SerialPortOnDataReceived; //<-- this event happens everytime when new data is received by the ComPort
        _serialPort.Open(); //<-- make the comport listen
        textBox1.Text = string.Format("Listening on {0}...", comboBox1.Text);

    //here i am trying @Adam Casey 's code and serialReceived thing doesn't work.
         byte[] serialReceived;
         string reading = Encoding.UTF8.GetString(serialReceived);
         textBox2.Text = reading.Substring(13);
    }
    private delegate void Closure();
    private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
    {
        if (InvokeRequired)     //<-- Makes sure the function is invoked to work properly in the UI-Thread
            BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));     //<-- Function invokes itself
        else
        {
            while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty
            {
                textBox1.Text += string.Format("{0:X2} ", _serialPort.ReadByte()); //<-- bytewise adds inbuffer to textbox
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我对Com端口和RS232的体验,如果你详细解决了我的问题,我可以提供帮助。

如果您的问题只是将基于字符串的十六进制值转换为ASCII,请使用以下内容。

         //41 is ACII 'A'
        String hs = "41";
        var x = Convert.ToUInt32(hs, 16);
        StringBuilder sb= new StringBuilder();
        sb.Append(Convert.ToChar(x))
        String s = sb.ToString();

根据您的评论编辑

033 ID_00:通过以下代码收集10.6公斤

 String hs = "x30 30 33 33 20 49 44 5F 30 30 3A 20 20 20 31 30 2E 36 20 6B 67 20 0D 0A 0D 0A";
            System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(hs, "([A-Z-0-9]{2}) ");
            StringBuilder sb = new StringBuilder();
            System.Text.RegularExpressions.Match m = match.NextMatch();
            while(m.Success)
            {
                var x = Convert.ToUInt32(m.Value.Trim(),16);
                sb.Append(Convert.ToChar(x));
               m= m.NextMatch();
            }


            String s = sb.ToString();

如果你有任何初始字符,你可以先将它子字符串,但这个正则表达式将为你提供。请注意这一点,您可以编写另一个重复文本来收集kg信息,例如: (.+?) kg是一种从ASCII表示中捕获kg信息的模式。