I would like to know how I would proceed in order to write some strings into one byte of a byte array (running C# WinForms in MS Visual 2015 Community edition).
I have a control board that controls a step motor. In order to send commands to the motor via the SerialPort
the board needs a byte array of length 9.
In each byte of the array there is an information stored (like board adress, motor number etc.) The last 3 bytes in this array are for the speed. From the source code of the program that the producer ships with it, sometimes the information that I need to send looks like this : "b0", "bc", "a7" etc. How can I write this into the array in the desired place. Currently, I have it like this:
private void button3_Click(object sender, EventArgs e)
{
byte[] a = new byte[9];
a[0] = 1;
a[1] = 1;
a[2] = 0;
a[3] = 0;
a[4] = 0;
a[5] = 0;
a[6] = 02; //could also be like "bc"
a[7] = Convert.ToByte("bc"); // if its a number from 00 to
a[8] = Convert.ToByte("c0"); // 99 the motor works as planned
serialPort1.Write(a, 0, a.Length);
}
If I have normal numbers from 0 to 99 in byte 6-9 the motor runs as intended. But higher speed have string values. Why the variables look the way they look I'll figure out later, but from my plan now a manual input would be fine as the motor is supposed to run at only one speed anyway.
So far my complete code does compile, but after sending I get :
FormatExceptionError{"Inputstring has wrong format."}
I found questions of how to convert a complete string into a complete byte array but those did not really help me.
You need to specify the base of the input string:
a[7] = Convert.ToByte("bc", 16);
a[8] = Convert.ToByte("c0", 16);
Base 16 is hexadecimal.
Those are not string values. They are hexadecimal representations of each byte. Use 0x
as a prefix to indicate hexadecimal values.
a[7] = 0xBC;
a[8] = 0xC0;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.