将ASCII字符串转换为整数字符串

时间:2011-03-04 01:33:50

标签: c# .net

我可以通过UDP读取一串字节但不能将它们转换为整数字符串。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

IPAddress类有一些辅助方法可以在网络和主机顺序之间来回转换字节,即:HostToNetworkOrderNetworkToHostOrder