0

I have a client that receive data from server in TCP/IP using C#. i've been able to display/print the data using in ASCII text format. But I don't know how to print the incoming data from stream in Hex? So, i don't have to convert it in ASCII. Because the HEX value representing an ID from a RFID reader.

And this is how i get the data in ASCII. How to make textBox1 display in HEX?

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 + " >> " + ;
        }

Edit : I've been able to display in HEX format but it will has so many 0 after the data. The amount of 0 will be depend on inStream byte size. How to overcome 0 after the data?

This is my new update code :

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 + " >> " + ;
        }
Rhizudeen
  • 47
  • 11
  • 1
    Possible duplicate of [How do you convert a byte array to a hexadecimal string, and vice versa?](https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa) – Simply Ged Mar 19 '18 at 10:34

1 Answers1

0

Try the following:

string hex = "";
foreach (char character in readData.ToCharArray())
{
    hex += String.Format("{0:X}", Convert.ToInt32(character));
}
textBox1.Text = hex;
Fabian S.
  • 76
  • 6
  • how to display in hex without using ASCII first in readData? because readData somehow only return "???"or question mark. I think because the character is not recognized by C#. – Rhizudeen Mar 19 '18 at 11:46