Console string input to hexdecimal

Huzo

New member
Joined
May 8, 2024
Messages
3
Programming Experience
Beginner
Hello everybody,

I am new to C# and .NET framework programming so hold your horses. I am trying to send some hex data to IO port (USB). I am able to send fixes data ( byte[] send = {0x01,0x01,0x80 }). Now I would like to convert string input from console to byte array. I was able to find some solutions but they are a little bit confusing for me. I need this now to manually control the device, later I will incorporate a CSVHelper to read from CSV file and write to a new one.

Solutions I have found are:
Split the string to string array, then parse that as int array, and parse that as byte. I am getting errors for that.
Second solution got me to use some other namespace but as I am new to C# and .NET I got totaly lost in it.

Can you help me?
 
I am still not sure about prefix as I am new to C#. I know that in C when calling uint8_t you need to putt 0x prefix so that compiler know that it is a hex data. But for byte in C# I am not sure.
To make it clear I want to pass string {0x01,0x01,0x80} (right now 0x is just to clarify that it must be hexdecimal) to byte array {0x01,0x01,0x80}.
So not a translation that ends up in some sort of a long hex data or wrong data. ASCII 01 to byte (hex) 01.
Sorry if I got you confused.
 
You can call Convert.ToByte, byte.Parse or byte.TryParse to convert hexadecimal text to a byte value. Pretty sure that they will not work if the "0x" prefix is included, so you'd have to trim that first if it is.
 
I have tried all of them and I am getting an error. Here is the code:
Main:
 {

   
     string msg;
     string[] middleMenMsg= Array.Empty<string>();
     int[] middleMen= Array.Empty<int>();
     byte[] ToSend= Array.Empty<byte>();
     //byte[] send = {0x01,0x01,0x80 };
     SerialPort port = new SerialPort();
     port.PortName = "COM6";
     port.BaudRate = 9600;
     port.Parity = Parity.None;
     port.DataBits = 8;
     port.StopBits = StopBits.One;
     port.ReadTimeout = 500;
     port.WriteTimeout = 500;
     Console.WriteLine("Write open to open port or close to close it");
     msg = Console.ReadLine();
     while (true)
     {
         if (msg == "open")
         {
             port.Open();
             msg = msg.Remove(0, msg.Length);
             if (port.IsOpen)
             {
                 Console.WriteLine("port is succesfully opened");

             }
             else
             {
                 Console.WriteLine("error port wont open");
             }
         }
         else if (msg == "close" && port.IsOpen)
         {
             port.Close();
             msg = msg.Remove(0, msg.Length);
             break;
         }
         msg = Console.ReadLine();
         if (msg != "close" || msg != "open")
         {


             middleMenMsg = msg.Split(',');
             Console.WriteLine(middleMenMsg.Length);
             foreach (string a in middleMenMsg)
             {
                 Console.WriteLine(a);

             }
             for (int k = 0; k <= middleMenMsg.Length; k++)
             {
                 ToSend[k] = Convert.ToByte(middleMenMsg[k]);
             }




             port.Write(ToSend, 0, ToSend.Length);
             msg = msg.Remove(0, msg.Length);
         }




     }  
   

 }

At lines 4-7 I am declaring the messages and needed temporary variables. From line 42 to line 63 I do conversion and sending to USB. First I was getting error for the array of bytes and strings managed to fix that by calling Array.Empty<>(). Now I am getting this in the console.

Write open to open port or close to close it
open
port is successfully opened
01,01,80
01
01
80

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at ConsoleApp1.Program.Main(String[] args) in C:\Users\Ivan.huzjak\source\repos\ConsoleApp1\ConsoleApp1\Program.cs:line 70
Line 70 should be this line of code: ToSend[k] = Convert.ToByte(middleMenMsg[k]); here it is at line 55.
 
You have this:
C#:
byte[] ToSend= Array.Empty<byte>();
and then you have the line that throws the exception, with no reference to ToSend in between. If that array is empty, no index is valid, so that exception is inevitable. Presumably you want ToSend to refer to an array that is the same length as middleMenMsg, so you need to create that array. Don't use Array.Empty at all if you're not going to use those empty arrays. Just declare the variables and then assign the actual array you want to use when you can do so.
 
May I suggest using a List<byte> instead. That way you can simply append to list as you parse each "value" from the console.
 
As an aside, if you can get the user to input the hex values without spaces or commas, then Convert.FromHexString() is another possible option.

Sample usage:
C#:
foreach(byte b in Convert.FromHexString("0BADF00D"))
    Console.WriteLine("{0:X2}", b);

You can play with it some more with this .NET Fiddle: Using FromHexString() | C# Online Compiler | .NET Fiddle
 
Back
Top Bottom