0

I can read a string of bytes via UDP but cannot convert them to a string of integers.

try {

       IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

      // Blocks until a message returns on this socket from a remote host.

       Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
       string returnData = Encoding.ASCII.GetString(receiveBytes);

        // Uses the IPEndPoint object to determine which host responded
       Console.WriteLine("Received: \n\n " +
                                          returnData.ToString());
       Console.WriteLine("\nSource:\n\n " +
                                         "IP: " + RemoteIpEndPoint.Address.ToString() +
                                         "\n Port: " +
                                         RemoteIpEndPoint.Port.ToString());

        //split string by delimiter
        string[] arrString = returnData.Split(new char[] { ',' });

        int[] data = new int[arrString.Length];

        for (int i = 0; i < arrString.Length; i++)
        {

          data[i] = int.Parse(arrString[i]);


         }


         System.Threading.Thread.Sleep(500000000);
         // udpClient.Close();


          }  
       catch (Exception e ) {
                  Console.WriteLine("\nError: \n");
                  Console.WriteLine(e.ToString());
                  System.Threading.Thread.Sleep(500000000);
        };
4
  • What's the error you're getting? And is the string you receive actually a comma-separated list of single digits? Commented Mar 4, 2011 at 1:45
  • What's the problem? Is it slow? Try a smaller Sleep(). Commented Mar 4, 2011 at 1:48
  • The byte array looks like the following: ??, ??, ??, ?? Commented Mar 4, 2011 at 2:03
  • Other guys had answered the question, just consider usingConsole.ReadKey() instead of System.Threading.Thread.Sleep(500000000) for pausing application. Commented Mar 4, 2011 at 5:34

2 Answers 2

1

How to: Convert a byte Array to an int (C# Programming Guide)

byte[] bytes = { 0, 0, 0, 25 };

// If the system architecture is little-endian (that is, little end first),
// reverse the byte array.
if (BitConverter.IsLittleEndian)
    Array.Reverse(bytes);

int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
// Output: int: 25
Sign up to request clarification or add additional context in comments.

Comments

0

The IPAddress class has some helper methods to convert bytes back and forth between network and host order, namely: HostToNetworkOrder and NetworkToHostOrder

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.