## CRC16, CRC32, CRC32C checksums

### Introduction

The concept of error detection codes was first proposed by mathematician and computer scientist W. Wesley Peterson in his 1961 publication Cyclic Codes for Error Detection.

### CRC-32

```crc32x:
_crc32x:
lea    esi, [esp+32+4]
lodsd
xchg   edx, eax          ; edx = crc
not    edx
lodsd
xchg   ecx, eax          ; ecx = inlen
lodsd
xchg   esi, eax          ; esi = in
xor    eax, eax          ; eax = 0
jecxz  crc_l3            ; if (inlen==0) return crc;
crc_l0:
lodsb                    ; al = *p++
xor    dl, al            ; crc ^= al
xchg   eax, ecx
mov    cl, 8
crc_l1:
shr    edx, 1            ; crc >>= 1
jnc    crc_l2
xor    edx, 0xEDB88320
crc_l2:
loop   crc_l1
xchg   eax, ecx
loop   crc_l0
crc_l3:
not    edx
mov    [esp+28], edx     ; return ~crc
ret
```

CRC-32C (Castagnoli)

In 2007, two years before Peterson’s death, Intel added a new instruction simply called CRC32. It expects a byte in AL before computing CRC32 in EDX using the polynomial 0x82F63B78. Here’s code to emulate the instruction should it be unavailable.

```crc32cx:
_crc32cx:
lea    esi, [esp+32+4]
lodsd
xchg   edx, eax          ; edx = crc
lodsd
xchg   ecx, eax          ; ecx = inlen
lodsd
xchg   esi, eax          ; esi = in
xor    eax, eax          ; eax = 0
jecxz  crcc_l3            ; if (inlen==0) return crc;
crcc_l0:
lodsb                    ; al = *p++
xor    dl, al            ; crc ^= al
xchg   eax, ecx
mov    cl, 8
crcc_l1:
shr    edx, 1            ; crc >>= 1
jnc    crcc_l2
xor    edx, 0x82F63B78
crcc_l2:
loop   crcc_l1
xchg   eax, ecx
loop   crcc_l0
crcc_l3:
mov    [esp+28], edx     ; return crc