Create CRC from String

Gerald Oakham 41 Reputation points
2022-09-21T16:31:28.993+00:00

Hi,
I have been looking around the internet for a way to create a CRC from a String.
I have found many solutions, but the result I get out doesn't match what I know to be correct ( I am hardcoding the value at the moment, and the response I get back is correct ).

For example, If I send the following string to a device (- quotes),

    "A     273     SPA Reception 2          1        03                058"  

I get an "ACK" response back.

All the code I have found and run gives me a different value to 058.

The value is created by XORing the Chars with the preceding one.

243496-screenshot-2022-09-21-172607.gif

Can someone please advise me on how I can, in C#, get the required answer?

thank you

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,096 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 53,426 Reputation points
    2022-09-22T20:08:15.7+00:00

    tweeting the original sample code, it return 58

    using System;  
      
    class GFG  
    {  
    	static int XorAscii(String str)  
    	{  
    		int ans = (str[0]);  
    		for (int i = 1; i < str.Length; i++) {  
    			ans = (ans ^ ((str[i])));  
    		}  
    		return ans;  
    	}  
      
    	// Driver code  
    	public static void Main(String[] args)  
    	{  
    		var str = "A     273     SPA Reception 2          1        03                0";  
    		var crc = XorAscii(str).ToString("X2");  
    		Console.WriteLine(str + crc);  
    	}  
    }  
      
    

1 additional answer

Sort by: Most helpful
  1. Viorel 110.7K Reputation points
    2022-09-21T18:06:43.103+00:00

    Check an example for your picture:

    string example = "D 3956";  
      
    int crc = example.Aggregate( 0, ( a, b ) => a ^ b );  
      
    string crc_s = crc.ToString( "X2" );  
    byte crc1 = (byte)crc_s[0];  
    byte crc2 = (byte)crc_s[1];  
      
    // show the results:  
    Console.WriteLine( "crc1={0:X2}, crc2={1:X2}", crc1, crc2 );