How to resolve the algorithm CRC-32 step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm CRC-32 step by step in the Nim programming language

Table of Contents

Problem Statement

Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.

The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC. For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm CRC-32 step by step in the Nim programming language

Source code in the nim programming language

import strutils

type TCrc32* = uint32
const InitCrc32* = TCrc32(0xffffffff)

proc createCrcTable(): array[0..255, TCrc32] =
  for i in 0..255:
    var rem = TCrc32(i)
    for j in 0..7:
      if (rem and 1) > 0: rem = (rem shr 1) xor TCrc32(0xedb88320)
      else: rem = rem shr 1
    result[i] = rem

# Table created at compile time
const crc32table = createCrcTable()

proc crc32(s: string): TCrc32 =
  result = InitCrc32
  for c in s:
    result = (result shr 8) xor crc32table[(result and 0xff) xor byte(c)]
  result = not result

echo crc32("The quick brown fox jumps over the lazy dog").int64.toHex(8)


  

You may also check:How to resolve the algorithm Documentation step by step in the Stata programming language
You may also check:How to resolve the algorithm Strip comments from a string step by step in the Quackery programming language
You may also check:How to resolve the algorithm Enumerations step by step in the Shen programming language
You may also check:How to resolve the algorithm N'th step by step in the Raku programming language
You may also check:How to resolve the algorithm Generate lower case ASCII alphabet step by step in the Scala programming language