C# Help Needed

Status
Not open for further replies.

sodaant

Ars Praetorian
449
Subscriptor
I'm not a C# programmer, but I've been asked to add CRC checksum checking to some code that receives a string of data from a remote system via a wireless connection.

The data logging application in C# reads the data in the form of an ASCII string from the remote sensors. The last byte of the data string (immediately before the <CR> that terminates the data) is a binary CRC8 checksum. I need to compute the CRC8 value of the received string up to, but not including, the received CRC8 byte and the <CR> charater.

The problem is is that the CRC8 code that I've been given takes as its parameter a byte array rather than a string. The method definition looks like this:

public byte Checksum(params byte[] val)

How can I convert the string I have to something the Checksum() method can use?
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
A char in C# represents an abstract Unicode code point, not any particular representation (though it happens to be 16 bits). This is very different from C/C++ where the language defines char as essentially an uint8 that uses ASCII semantics when converting to/from string literals. Long story short, string.toCharArray is not the answer.

How is the data being read, exactly? In C# you should be using one or more classes derived from Stream. If it's a reasonable size to hold in RAM, just use a MemoryStream on both ends and you're done: it works with raw byte arrays by default. If the input code is using something like TextReader instead, that's dumb, but still manageable. You just need to see which Encoding class is being used to convert the network buffer into a string, then use WhateverBuffer.GetBytes() in your CRC code.
 

crxs

Ars Tribunus Militum
2,587
Subscriptor
In SerialPort.ReadExisting() a conversion happens. The bytes are converted to a string using the encoding specified in SerialPort.Encoding. Instead of getting the bytes converted to a string by the SerialPort class and then converting that back to bytes you should get the bytes directly, using something like
Code:
int bytesToRead = comport.BytesToRead;
byte[] data = new byte[bytesToRead];
comport.Read(data, 0, bytesToRead);
and then, after checking the the checksum, convert them into a string:
Code:
string dataString = System.Text.Encoding.ASCII.GetString(data);
(Assuming that ReadExisting and BytesToRead read the same amount of data and don't treat caching differently.)
 
Status
Not open for further replies.