0

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");

        }
    }

1 Answers1

0

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);    
  • I revised it according to your suggestion, anyway it works partially. I got the first few word as I desired, but later on uncountable "00000" was printed out, and it never stop. Anyone knows why it goes like this way? – user2863859 Mar 18 '14 at 06:04
  • @user2863859 what is the input you are giving? – NullReferenceException Mar 18 '14 at 06:06
  • @user2863859 check for inputs here – NullReferenceException Mar 18 '14 at 06:22
  • @user2863859 for ex:byte[] data = new byte[] { 0x33, 0x43, 0xFE } ; string hexString = BitConverter.ToString(data);Output : "33-43-FE" – NullReferenceException Mar 18 '14 at 06:27
  • Thanks for your help, but the problem is still there. I print out the outgoing messages on my computer to check if I can send the right messages. The printout looks exactly right. But on the receiving terminal I can only receive the beginning of the messages, the following messages are all changed to a nonstop serial of "0". The printout never stop on Receiving side even after the sending program stopped. – user2863859 Mar 21 '14 at 15:56
  • Please don't put the code in while() loop,because this will be infinite loop or there is no exit of the while() loop,it is always true. – NullReferenceException Mar 21 '14 at 16:04