Question

I'm doing a simple control CRC to a project of mine, which sends data via serial port to an Arduino.

I'm trying to calculate the CRC of the message: A0h 45h 11h 83h or 69d 17d 160d 131d

Turned to string, which gives the message to calculate: "Eá◄â" By turning to ASCII returns the result: 69d 63d 63d 63d

Why did this happen? Code is below

tks

public byte CalculateCRC(string data)
{
    data = "Eá◄â";
    byte[] characters = new byte[System.Text.Encoding.ASCII.GetByteCount(data)];
    characters = System.Text.Encoding.ASCII.GetBytes(data);

    byte result = 0;
    foreach (byte character in characters )
        result = (byte)(result + character);
    result = (byte)(result + 1);
    return result;
}
Was it helpful?

Solution

Encoding.ASCII Property:

ASCII characters are limited to the lowest 128 Unicode characters, from U+0000 to U+007F.

So don't turn the input A0h 45h 11h 83h or 69d 17d 160d 131d into a string, but create a byte array out of it.

OTHER TIPS

It may well be that you want the encoding Latin1 aka ISO-8859-1 aka CP28591.

This encoding will map all bytes with hex values in the range 0-255 to the Unicode character with the same hex value - convenient for roundtripping values to be sent to a serial port.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top