0

hey guys i recently created a c# winform program by using serial port. Im sending and receving data using user textbox and i wanna display "receiving messages" in binary format. I created an array and i think i need to pull from array one by one but im not sure. Here is my unfinished code, can somebody help me figure out.

namespace serialchannel

{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        foreach (String s in System.IO.Ports.SerialPort.GetPortNames())
        {
            portNames.Items.Add(s);
        }
    }

    public System.IO.Ports.SerialPort sport;

    private void ConnectButton_Click(object sender, EventArgs e)
    {

        String port = portNames.Text;
        int baudrate = Convert.ToInt32(baudRates.Text);
        Parity parity = (Parity)Enum.Parse(typeof(Parity), parityType.Text);

        SerialPortConnect(port, baudrate, parity);

    }
    public void SerialPortConnect(String port, int baudrate, Parity parity)
    {
        sport = new System.IO.Ports.SerialPort(port, baudrate);
        try
        {
            sport.Open();

            sport.DataReceived += new SerialDataReceivedEventHandler(SportDataReceived);
            if (sport.IsOpen)
            {
                signal.Visible = true;
                signal.Text = "connection successful";
                signal.ForeColor = Color.Green;
            }
            else
            {
                signal.Visible = true;
                signal.Text = "connection err";
                signal.ForeColor = Color.Red;
            }

        }
        catch (Exception ex) { Console.WriteLine("err", ex); }           
    }
    private void SportDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        displayedTextBox.AppendText( "received:"+ sport.ReadExisting()+ "\n");
    }

    private void SendButton_Click(object sender, EventArgs e)
    {

        String data = userInputTextBox.Text;
        sport.Write(data);
        **byte []arr = System.Text.Encoding.ASCII.GetBytes(data);**


        
        displayedTextBox.AppendText(Environment.NewLine + "sent:" + data);
    }
    
    private void CloseButton_Click(object sender, EventArgs e)
    {

        if (sport.IsOpen)
        {
            sport.Close();
            displayedTextBox.AppendText(Environment.NewLine + "disconnected");
        }
    }

    private void baudRates_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}

1 Answer 1

0

You are almost there. It is hard to tell what you want to do, from the way your question is phrased. Do you want to display the text Receiving Data, as in that specific text, but in binary? Or did you want to take the line that has the two asterisks on either side and convert that data to binary? I will assume the latter.

By the "line surrounded by double asterisks," I specifically mean your code

byte []arr = System.Text.Encoding.ASCII.GetBytes(data);

As we know, binary is 0s and 1s. Each zero and each one is a bit, and each element of the array arr is a byte, which is always 8 bits long (at least, in the ASCII encoding, it is). Binary is what is known as a base-2 number system.

Per the question asked and answered over here on another Stack Overflow question, for each individual byte in your array, arr, you can represent it in binary via the following:

string yourByteString = Convert.ToString(byteArray[20], 2).PadLeft(8, '0');

As per the Microsoft documentation, the specific overload of ToString used is one that takes the current element of the byteArray, and represents it as a string in Base 2 which is binary.

The PadLeft method then pads it on then left with zeros in case the byte you are converting cannot be represented with 8 binary digits.

Let's create a new class in our project, say ByteToBinaryConverter and let's make it a static class. Furthermore, let's make our conversion method an extension method of byte, so that we can use it in a fluent (easy-to-read code) manner:

namespace serialchannel
{
    public static class ByteToBinaryConverter
    {
        public static string ToBinaryString(this byte byteToConvert)
        {
            return Convert.ToString(byteToConvert, 2).PadLeft(8, '0');
        }
    }
}

Now, let's use the method in your SendButton_Click event handler method. I am going to repeat the code of that method here, with /* ... */ meaning ignore everything else, and calling our new method:

namespace serialchannel
{
    public static class ByteToBinaryConverter
    {
        public static string ToBinaryString(this byte byteToConvert)
        {
            return Convert.ToString(byteToConvert, 2).PadLeft(8, '0');
        }
    }

    public class Form1 : Form
    {
        /* ... rest of class ... */
        
        private void SendButton_Click(object sender, EventArgs e)
        {
            var data = userInputTextBox.Text;
            sport.Write(data);
            
            var arr = System.Text.Encoding.ASCII.GetBytes(data);
            
            var textToBeDisplayed = "";
            foreach(var element in arr)
            {
                textToBeDisplayed += element.ToBinaryString();
            }
            
            displayedTextBox.AppendText(Environment.NewLine + "sent: " + textToBeDisplayed);
        }
        
        /* ... rest of class ... */

    }
}

Notice the use of the var keyword instead of explicit data types. This makes use of Local variable type inference features of C# 3.0. Using the var keyword saves you from having to use explicit types in your code for variables. The C# compiler can figure it out based on what data you are initializing the variable with.

If you want to use explicit types, then I suggest the following variation of the code:

namespace serialchannel
{
    public static class ByteToBinaryConverter
    {
        public static string ToBinaryString(this byte byteToConvert)
        {
            return Convert.ToString(byteToConvert, 2).PadLeft(8, '0');
        }
    }
    
    public class Form1 : Form
    {
        /* ... rest of class ... */
        
        private void SendButton_Click(object sender, EventArgs e)
        {
            string data = userInputTextBox.Text;
            sport.Write(data);
            
            byte[] arr = System.Text.Encoding.ASCII.GetBytes(data);
            
            string textToBeDisplayed = "";
            foreach(byte element in arr)
            {
                textToBeDisplayed += element.ToBinaryString();
            }
            
            displayedTextBox.AppendText(Environment.NewLine + "sent: " + textToBeDisplayed);
        }
        
        /* ... rest of class ... */

    }
}

Above, I am using all lowercase versions of the type names; i.e., I am saying string not String as you have it. There really is no appreciable difference but it looks cleaner this way, in my opinion.

Sign up to request clarification or add additional context in comments.

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.