Search code examples
c#ord

How to convert network byte to int?


Reading UDP packet, need to convert a single byte to ordinal value (int). Or a 4 byte integer value to int. But the value I am interested is a 0, 1, or 2 - single byte of significance - so don't really need to read all 4 bytes.

private async void Button1_ClickAsync(object sender, EventArgs e)
{
   try
   {
      using (var TheudpClient = new UdpClient(2237))
      {
         TheudpClient.Client.SetSocketOption(SocketOptionLevel.Socket,            SocketOptionName.ReuseAddress, true);

         var receivedResults = await TheudpClient.ReceiveAsync();

         MsgText = Encoding.ASCII.GetString(receivedResults.Buffer);

         MsgTypeStr = MsgText.Substring(11,1);


         MsgTypeInt = (int)MsgTypeStr; // this line blows up...  

     //  MsgTypeInt = int.Parse(MsgTypeStr, System.Globalization.NumberStyles.HexNumber);  // this blows up

     //  MsgTypeInt = Int32.Parse(MsgTypeStr); // this blows up


         richTextBox1.Text = "\nLength: " + MsgText.Length + " Type " + MsgTypeInt.ToString();
         richTextBox1.Text = "\nReceived data: " + MsgText;

        }
     }
     catch(Exception ex)
     {
         richTextBox1.Text += "\nException: " + ex.Message.ToString();
     }
}

Error msg is "Input string was not in a correct format."

I believe the issue is trying to convert a string byte into an int. In Delphi its easy with the Ord function. I likely need to convert from a char to an int. Just don't know how to get to char from string.

I am new to C#. Thanks for any suggestions.


Solution

  • When you cast a string to an int, it tries to read the string as if it were a formatted number. But what you want to do is convert the first byte in the string, like this:

    MsgTypeInt = (int)(MsgText[11]);
    

    Caveats: haven't compiled or tried this, and also haven't investigated how many bytes per character is returned from Encoding.ASCII.GetString.