I have a serial device which sends me a string of ASCII Hex codes (e.g. 42 33). I then read these in and use them to bit rotate a checksum. Once they have been rotated I need to send them back to the serial device including some control bytes.
I feel my code may be overcomplicated and I am struggling to create a clean way to build a series of bytes to send back to the device.
// Calculate Checksum
private byte[] calcChecksum(string checksum)
{
// Create a byte array from checksum string
byte[] byteArray = Encoding.ASCII.GetBytes(checksum);
// Create Hex Characters from ASCII codes of byte array positions 5, 6.
string left = ((char)byteArray[5]).ToString();
string right = ((char)byteArray[6]).ToString();
// Convert Hex Characters to Integer values used for the shifting
int numLeft = Convert.ToByte(left, 16);
int numRight = Convert.ToByte(right, 16);
// Dummy checksum values to shift
string cs = ShiftLeft(0x5232, numLeft).ToString("x4");
string kw = ShiftRight(0xab23, numRight).ToString("x4");
string cskw = cs + kw;
byte[] checksumBytes = Encoding.ASCII.GetBytes(cskw);
return checksumBytes;
}
// Communicate with Serial device
private void bChecksum_Click(object sender, EventArgs e)
{
// Read string from device. Need a better way to create this
// instead of using a richtext box. Okay for now but suggestions
// welcome.
returnCode = tbOutput.Text;
byte[] checksumBytes = calcChecksum(returnCode);
// Bytes I need to send to the device. Here I need to insert all the
// checksumBytes Array values between 0x1B and 0x03
byte[] bytesToSend = { 0x04, 0x02, 0x31, 0x30, 0x1B, ...array bytes..., 0x03 };
_serialPort.Write(bytesToSend, 0, bytestosend.Length);
}
To clarify I need a way to insert the checksumBytes Array into the bytesToSend Array in between the 0x1B and 0x03 positions.
Additionally any code improvements would be most welcome.