如何在tcp / ip C#客户端中以十六进制打印传入的流数据?

时间:2018-03-19 10:31:06

标签: c# networking tcp hex ascii

我有一个客户端使用C#从TCP / IP服务器接收数据。我能够以ASCII文本格式显示/打印数据。但我不知道如何从十六进制流中打印传入数据?所以,我不必用ASCII转换它。因为HEX值代表来自RFID阅读器的ID。

这就是我用ASCII获取数据的方式。如何在HEX中显示textBox1?

private void getMessage()
        {
            while (true)
            {
                serverStream = clientSocket.GetStream();
                int buffSize = 0;
                byte[] inStream = new byte[10025];
                buffSize = clientSocket.ReceiveBufferSize;
                serverStream.Read(inStream, 0, buffSize);
                string returndata = System.Text.Encoding.ASCII.GetString(inStream);
                readData = "" + returndata;
                msg();
            }
        }

        private void msg()
        {
            if (this.InvokeRequired)
                this.Invoke(new MethodInvoker(msg));
            else
                textBox1.Text += readData;// textBox1.Text + Environment.NewLine + " >> " + ;
        }

编辑: 我已经能够以HEX格式显示,但数据之后会有这么多0。 0的数量取决于inStream字节大小。如何在数据后克服0?

这是我的新更新代码:

private void getMessage()
        {
            while (true)
            {
                serverStream = clientSocket.GetStream();
                int buffSize = 0;
                byte[] inStream = new byte[10];
                buffSize = clientSocket.ReceiveBufferSize;
                serverStream.Read(inStream, 0, inStream.Length);
                string returndata = ByteArrayToString(inStream);//System.Text.Encoding.ASCII.GetString(inStream);

                //MessageBox.Show(returndata);
                readData = returndata;//"" + returndata;
                msg();
            }
        }

        private void msg()
        {
            if (this.InvokeRequired)
                this.Invoke(new MethodInvoker(msg));
            else
                textBox1.Text += readData;// textBox1.Text + Environment.NewLine + " >> " + ;
        }

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

string hex = "";
foreach (char character in readData.ToCharArray())
{
    hex += String.Format("{0:X}", Convert.ToInt32(character));
}
textBox1.Text = hex;