cancel
Showing results for 
Search instead for 
Did you mean: 

CRC32 calculation in C#

lukas239955
Associate
Posted on August 04, 2014 at 10:47

Hi,

I created a C# class which calculates the CRC32 checksum exactly like the STM This may be useful to others:

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Security.Cryptography;
namespace
JCC224_User_Interface
{
public
static
class
CRC32
{
public
static
UInt32 calculateWord(UInt32 crc, UInt32 data)
{
int
i;
crc = crc ^ data;
for
(i = 0; i < 32; i++)
{
if
((crc & 0x80000000) != 0)
{
crc = (crc << 1) ^ 0x04C11DB7; 
// Polynomial used in STM32
}
else
{
crc = (crc << 1);
}
}
return
(crc);
}
public
static
UInt32 calculateBuffer(UInt32 initial_value, UInt32[] buffer)
{
for
(
int
i = 0; i < buffer.Length; i++)
{
initial_value = calculateWord(initial_value, buffer[i]);
}
return
initial_value;
}
}
}

#crc32
2 REPLIES 2
Posted on August 04, 2014 at 16:37

https://community.st.com/0D50X00009XkYj5SAF

 

https://community.st.com/0D50X00009XkbNMSAZ

 

https://community.st.com/0D50X00009XkZVESA3

 

Edit: fixing DEAD LINKs, original post from Aug 2014

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
kristian faulkner
Associate
Posted on February 14, 2018 at 18:34

Greetings all,

I independently wrote thisC# code and verified this is working. Enjoy.

I also want to add that Ispent a lot of time working with the Keil debugger -- DO NOT TRUST THE DEBUGGER FOR CRC. Always work out your CRC value using code, not the debug windows. The debug window gives you an incorrect CRC value (e.g.0x12345678 -> 0x877BB728 and not the correct value of0xDF8A8A2B).

 public static UInt32 ComputeSTM32Checksum(UInt32[] inputData, UInt32 initial = 0xFFFFFFFF, UInt32 polynomial = 0x04C11DB7)
 {
 UInt32 crc = initial;
 foreach (UInt32 current in inputData)
 {
 crc ^= current;
 // Process all the bits in input data.
 for (uint bitIndex = 0; (bitIndex < 32); ++bitIndex)
 {
 // If the MSB for CRC == 1
 if ((crc & 0x80000000) != 0)
 {
 crc = ((crc << 1) ^ polynomial);
 }
 else
 {
 crc <<= 1;
 }
 }
 }
 return crc;
 }�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?

Tests to check:

uint result1 = ComputeSTM32Checksum(new uint[] { 0x12345678 });
Trace.Assert(result1 == 0xDF8A8A2B);
uint result2 = ComputeSTM32Checksum(new uint[] { 0x8E09BAF6 });
Trace.Assert(result2 == 0x5C00CC44);
uint result3 = ComputeSTM32Checksum(new uint[] { 0x12345678, 0x8E09BAF6 });
Trace.Assert(result3 == 0x04F1F147);
uint result4 = ComputeSTM32Checksum(new uint[] { 0x8E09BAF6, 0x12345678 });
Trace.Assert(result4 == 0x90B2EE2D);�?�?�?�?�?�?�?�?