Question

I want to get a hex type data using getstring, but I don't know C# very well. How can I modified the code to implement the function? I have a device keep sending the hex data to my PC via socket. I find the socket program below to receive the hex type data, but later the display of the receiving data are totally messy code that doesn't make any sense. I don't know if I use the wrong type of data or some problems else. Can anyone help me to solve it, thanks a lot!

I revised my program according to the suggestions, it give me some string as I desired, but later a serial of 000000 was printed out, and it never stop. Why it happened like this?

 public void ReceiveMsg()
    {
        while (true)
        {
            byte[] data = new byte[1024];
            int recv = newclient.Receive(data);
            Encoding.UTF8.GetString(data, 0, recv);
            string hexString = BitConverter.ToString(data).Replace("-", string.Empty);
            //string stringdata = Encoding.UTF8.GetString(data, 0, recv);
            showMsg(hexString + "\r\n");

        }
    }
Was it helpful?

Solution

This statement will covert your Byte Array to string.

string stringdata = Encoding.UTF8.GetString(data, 0, recv);

The following code converts Byte Array to Hex string

StringBuilder hexString = new StringBuilder(data.Length * 2);
foreach (byte b in data)
   hexString.AppendFormat("{0:x2}", b);

or you can use

string hexString = BitConverter.ToString(data);    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top