Movatterモバイル変換


[0]ホーム

URL:


Jump to content
Rosetta Code
Search

CRC-32

From Rosetta Code
Task
CRC-32
You are encouraged tosolve this task according to the task description, using any language you may know.


Task

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


The result should be in accordance with ISO 3309,ITU-T V.42,Gzip andPNG.

Algorithms are described onComputation 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:

The quick brown fox jumps over the lazy dog



11l

Translation of:C
V crc_table = [0] * 256L(i) 256   UInt32 rem = i   L 8      I rem [&] 1 != 0         rem >>= 1         rem (+)= EDB8'8320      E         rem >>= 1   crc_table[i] = remF crc32(buf, =crc = UInt32(0))   crc = ~crc   L(k) buf      crc = (crc >> 8) (+) :crc_table[(crc [&] F'F) (+) k.code]   R ~crcprint(hex(crc32(‘The quick brown fox jumps over the lazy dog’)))
Output:
414FA339

6502 Assembly

PRHEXEQU  $FDDA ; <= REPLACE THIS WITH THE PRHEX ROUTINE FOR YOUR MACHINEstringEQU  $EClengthEQU  $EEcrc0EQU  $FAcrc1EQU  $FBcrc2EQU  $FCcrc3EQU  $FDtable0EQU  $9200table1EQU  $9300table2EQU  $9400table3EQU  $9500ORG  $9114LDA #<textSTA  stringLDA #>textSTA  string+1LDA #$2b ; length of textSTA  lengthLDA #$00STA  length+1STA  crc0STA  crc1STA  crc2STA  crc3JSR  crc32LDA  crc3JSR  PRHEXLDA  crc2JSR  PRHEXLDA  crc1JSR  PRHEXLDA  crc0JMP  PRHEXtextASC 'The quick brown fox jumps over the lazy dog'; ORG  $916Ecrc32JSR  startLDY  stringSTX  stringloopLDA lengthBNE no_borrowLDA length+1BEQ ones_complementDEC length+1no_borrowDEC lengthLDA (string),YEOR  crc0TAXLDA  table0,XEOR  crc1STA  crc0LDA  table1,XEOR  crc2STA  crc1LDA  table2,XEOR  crc3STA  crc2LDA  table3,XSTA  crc3INYBNE  loopINC  string+1BNE  loopstarthave_tableLDX #$00BNE  loop4 ; LDX #$04 BNE ones_complementloop256LDA #$00STA  table3,XSTA  table2,XSTA  table1,XTXASTA  table0,XLDY #$08loop8LSR  table3,XROR  table2,XROR  table1,XROR  table0,XBCC  no_xorLDA  table3,XEOR #$EDSTA  table3,XLDA  table2,XEOR #$B8STA  table2,XLDA  table1,XEOR #$83STA  table1,XLDA  table0,XEOR #$20STA  table0,Xno_xorDEYBNE  loop8INXBNE  loop256ones_complementLDX #$04STX  have_table+1 ; self-modifyloop4DEXLDA  crc0,XEOR #$FFSTA  crc0,XTXABNE loop4RTS

Ada

Works with:GNAT
withAda.Text_IO;useAda.Text_IO;withGNAT.CRC32;useGNAT.CRC32;withInterfaces;useInterfaces;procedureTestCRCispackageIIOis newAda.Text_IO.Modular_IO(Unsigned_32);crc:CRC32;num:Unsigned_32;str:String:="The quick brown fox jumps over the lazy dog";beginInitialize(crc);Update(crc,str);num:=Get_Value(crc);IIO.Put(num,Base=>16);New_Line;endTestCRC;
Output:
16#414FA339#

Arturo

printcrc"The quick brown fox jumps over the lazy dog"
Output:
414FA339

ALGOL 68

[0:255]BITS crc_table;BOOL crc_table_computed := FALSE;PROC make_crc_table = VOID:   BEGIN       INT n, k;      FOR n FROM 0 TO 255 DO          BITS c := BIN n;         FOR k TO 8 DO             c := IF 32 ELEM c THEN                     16redb88320 XOR (c SHR 1)                 ELSE                    c SHR 1 FI OD; crc_table[n] := c      OD;      crc_table_computed := TRUE   END;PROC update_crc = (BITS crc, STRING buf) BITS:   BEGIN       BITS c := crc XOR 16rffffffff;      INT n;      IF NOT crc_table_computed THEN make_crc_table FI;      FOR n TO UPB buf DO          c := crc_table[ABS ((c XOR BIN ABS buf[n]) AND 16rff)] XOR (c SHR 8)      OD ;      c XOR 16rffffffff   END; PROC hex = (BITS x) STRING :   BEGIN      PROC hexdig = (BITS x) CHAR: REPR (IF ABS x ≤ 9 THEN ABS x + ABS "0"                                         ELSE ABS x - 10 + ABS "a" FI);      STRING h := "";      IF x = 16r0 THEN h := "0"      ELSE BITS n := x; WHILE h := hexdig (n AND 16rf) + h; n ≠ 16r0 DO    n := n SHR 4 OD      FI;      h   END;PROC crc = (STRING buf) BITS:   update_crc(16r0, buf);STRING s = "The quick brown fox jumps over the lazy dog";print(("CRC32 OF ", s, " is: ", hex (crc (s)), newline))
Output:
CRC32 OF The quick brown fox jumps over the lazy dog is: 0414fa339

Applesoft BASIC

Implementation using Binary ASCII

 0 DIM D$(1111):D$(0)="0":D$(1)="1":D$(10)="2":D$(11)="3":D$(100)="4":D$(101)="5":D$(110)="6":D$(111)="7":D$(1000)="8":D$(1001)="9":D$(1010)="A":D$(1011)="B":D$(1100)="C":D$(1101)="D":D$(1110)="E":D$(1111)="F" 1 Z$ =  CHR$ (8) +  CHR$ (8) +  CHR$ (8) +  CHR$ (8) +  CHR$ (8) +  CHR$ (8) +  CHR$ (8) +  CHR$ (8) +  CHR$ (8) +  CHR$ (8) 100 C$ = "00000000000000000000000000000000" 110 S$ = "The quick brown fox jumps over the lazy dog" 120  GOSUB 200"CRC32 130  PRINT D$( VAL ( MID$ (C$,1,4)))D$( VAL ( MID$ (C$,5,4)))D$( VAL ( MID$ (C$,9,4)))D$( VAL ( MID$ (C$,13,4)))D$( VAL ( MID$ (C$,17,4)))D$( VAL ( MID$ (C$,21,4)))D$( VAL ( MID$ (C$,25,4)))D$( VAL ( MID$ (C$,29,4)))"  "; 140  END  200  IF  LEN (S$) = 0 THEN  RETURN  210  GOSUB 280"XOR #$FFFFFFFF 220  FOR I = 1 TO  LEN (S$) 230 R$ = "00000000" +  MID$ (C$,1,24) 235  PRINT D$( VAL ( MID$ (C$,1,4)))D$( VAL ( MID$ (C$,5,4)))D$( VAL ( MID$ (C$,9,4)))D$( VAL ( MID$ (C$,13,4))); 236  PRINT D$( VAL ( MID$ (C$,17,4)))D$( VAL ( MID$ (C$,21,4)))D$( VAL ( MID$ (C$,25,4)))D$( VAL ( MID$ (C$,29,4)))" " MID$ (S$,I,1)Z$; 240 C =  ASC ( MID$ (S$,I,1)):O$ = "": FOR B = 1 TO 8:K =  INT (C / 2):O$ =  STR$ (C - K * 2) + O$:C = K: NEXT B 250 A = ( MID$ (C$,25,1) <  >  MID$ (O$,1,1)) * 128 + ( MID$ (C$,26,1) <  >  MID$ (O$,2,1)) * 64 + ( MID$ (C$,27,1) <  >  MID$ (O$,3,1)) * 32 + ( MID$ (C$,28,1) <  >  MID$ (O$,4,1)) * 16 251 A = ( MID$ (C$,29,1) <  >  MID$ (O$,5,1)) * 8 + ( MID$ (C$,30,1) <  >  MID$ (O$,6,1)) * 4 + ( MID$ (C$,31,1) <  >  MID$ (O$,7,1)) * 2 + ( MID$ (C$,32,1) <  >  MID$ (O$,8,1)) + A: GOSUB 300 260 C$ =  STR$ (( MID$ (R$,1,1) <  >  MID$ (T$,1,1))) +  STR$ (( MID$ (R$,2,1) <  >  MID$ (T$,2,1))) +  STR$ (( MID$ (R$,3,1) <  >  MID$ (T$,3,1))) +  STR$ (( MID$ (R$,4,1) <  >  MID$ (T$,4,1))) 261 C$ = C$ +  STR$ (( MID$ (R$,5,1) <  >  MID$ (T$,5,1))) +  STR$ (( MID$ (R$,6,1) <  >  MID$ (T$,6,1))) +  STR$ (( MID$ (R$,7,1) <  >  MID$ (T$,7,1))) +  STR$ (( MID$ (R$,8,1) <  >  MID$ (T$,8,1))) 262 C$ = C$ +  STR$ (( MID$ (R$,9,1) <  >  MID$ (T$,9,1))) +  STR$ (( MID$ (R$,10,1) <  >  MID$ (T$,10,1))) +  STR$ (( MID$ (R$,11,1) <  >  MID$ (T$,11,1))) +  STR$ (( MID$ (R$,12,1) <  >  MID$ (T$,12,1))) 263 C$ = C$ +  STR$ (( MID$ (R$,13,1) <  >  MID$ (T$,13,1))) +  STR$ (( MID$ (R$,14,1) <  >  MID$ (T$,14,1))) +  STR$ (( MID$ (R$,15,1) <  >  MID$ (T$,15,1))) +  STR$ (( MID$ (R$,16,1) <  >  MID$ (T$,16,1))) 264 C$ = C$ +  STR$ (( MID$ (R$,17,1) <  >  MID$ (T$,17,1))) +  STR$ (( MID$ (R$,18,1) <  >  MID$ (T$,18,1))) +  STR$ (( MID$ (R$,19,1) <  >  MID$ (T$,19,1))) +  STR$ (( MID$ (R$,20,1) <  >  MID$ (T$,20,1))) 265 C$ = C$ +  STR$ (( MID$ (R$,21,1) <  >  MID$ (T$,21,1))) +  STR$ (( MID$ (R$,22,1) <  >  MID$ (T$,22,1))) +  STR$ (( MID$ (R$,23,1) <  >  MID$ (T$,23,1))) +  STR$ (( MID$ (R$,24,1) <  >  MID$ (T$,24,1))) 266 C$ = C$ +  STR$ (( MID$ (R$,25,1) <  >  MID$ (T$,25,1))) +  STR$ (( MID$ (R$,26,1) <  >  MID$ (T$,26,1))) +  STR$ (( MID$ (R$,27,1) <  >  MID$ (T$,27,1))) +  STR$ (( MID$ (R$,28,1) <  >  MID$ (T$,28,1))) 267 C$ = C$ +  STR$ (( MID$ (R$,29,1) <  >  MID$ (T$,29,1))) +  STR$ (( MID$ (R$,30,1) <  >  MID$ (T$,30,1))) +  STR$ (( MID$ (R$,31,1) <  >  MID$ (T$,31,1))) +  STR$ (( MID$ (R$,32,1) <  >  MID$ (T$,32,1))) 270  NEXT I 280 B$ = "": FOR B = 1 TO 32:B$ = B$ +  STR$ (( MID$ (C$,B,1) <  > "1")): NEXT B:C$ = B$ 290  RETURN  300  IF  NOT T THEN  DIM T$(255): FOR T = 0 TO 38: READ J: READ T$(J): NEXT T 310  IF  LEN (T$(A)) THEN T$ = T$(A): RETURN  320 R = A:T$ = "": FOR B = 1 TO 8:N =  INT (R / 2):T$ =  MID$ ("01",R - N * 2 + 1,1) + T$:R = N: NEXT B:T$ = "000000000000000000000000" + T$ 330  FOR J = 0 TO 7 340 X =  VAL ( MID$ (T$,32,1)) 350 T$ = "0" +  MID$ (T$,1,31) 360  IF X THEN B$ = "": FOR B = 1 TO 32:B$ = B$ +  MID$ ("01",( MID$ (T$,B,1) <  >  MID$ ("11101101101110001000001100100000",B,1)) + 1,1): NEXT B:T$ = B$ 370  NEXT J 380 T$(A) = T$:T = T + 1 390  RETURN  600  DATA171,01000001000001000111101001100000 610  DATA247,00100011110110010110011110111111 620  DATA95,11111011110101000100110001100101 630  DATA217,11111111000011110110101001110000 640  DATA213,11110110101110010010011001011011 650  DATA179,01010010011010001110001000110110 660  DATA141,10010011000010011111111110011101 670  DATA90,10001011101111101011100011101010 680  DATA224,10100000000010101110001001111000 690  DATA187,01011100101100110110101000000100 700  DATA169,10101111000010100001101101001100 710  DATA60,00101111011011110111110010000111 720  DATA128,11101101101110001000001100100000 730  DATA36,00111100000000111110010011010001 740  DATA235,00110111110110000011101111110000 750  DATA229,11010000011000000001011011110111 760  DATA77,00001000011011010011110100101101 770  DATA167,01001000101100100011011001001011 780  DATA1,01110111000001110011000010010110 790  DATA119,11001110011000011110010010011111 800  DATA96,01001101101100100110000101011000 810  DATA158,00010111101101111011111001000011 820  DATA68,01110001101100011000010110001001 830  DATA56,00101000000000101011100010011110 840  DATA193,11101100011000111111001000100110 850  DATA87,11110101000011111100010001010111 860  DATA160,11010110110101101010001111101000 870  DATA2,11101110000011100110000100101100 880  DATA30,11111010000011110011110101100011 890  DATA7,10011110011001001001010110100011 900  DATA26,11111101011000101111100101111010 910  DATA85,00011011000000011010010101111011 920  DATA15,10010000101111110001110110010001 930  DATA201,11100010101110000111101000010100 940  DATA188,11000010110101111111111110100111 950  DATA0,00000000000000000000000000000000 960  DATA238,01000111101100101100111101111111 970  DATA181,10111011000010110100011100000011 980  DATA114,10111110000010110001000000010000

Using 6502 Assembly

 0  HIMEM: 372308A=37229:P$=" 'Q$L.L%BP#%GKSFGFB1LEZ*=!4E[-Z=!6EW-[=!TEX-W=!U-XHPR?MPN<!PJ)!7!U7!T7!607!49&^!U+!T+!6+!43 =!UIM7!U=!TI87!T=!6IC7!6=!4I 7!4/POAP;<D2(Q>5ZIYUZ0PV@"9FORI=1TOLEN(P$):B$=MID$("D2A0--A6Q4Q5A8Q7Q8Q9R0M6--N3N4N6N8R7O2O4O6S1O7P7S4Q0--S7Q2S9U2X0J6X2X8N1A4G9T8X9U0H3H4Y0X6X7U6U7U8O5V0L5O8O9Y6Z2Z3Z5Z0Z1----J4",(ASC(MID$(P$,I))-32)*2+1,2):POKEA+I,(ASC(MID$(B$,1))-65)*10+ASC(MID$(B$,2))-48:NEXT 100 S$ = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG" 110  FOR I = 2 TO  LEN (S$) 120 C =  ASC ( MID$ (S$,I,1)) 130 C$ =  CHR$ (C + 32 * (C >  =  ASC ("A") AND C <  =  ASC ("Z"))) 140 S$ =  LEFT$ (S$,I - 1) + C$ +  MID$ (S$,I + 1, LEN (S$) - I) 150  NEXT  155  PRINT  MID$ (S$,1,0 *  FRE (0)); 160  POKE 236, PEEK (131) 170  POKE 237, PEEK (132) 180 A =  PEEK (236) +  PEEK (237) * 256 190  POKE 236, PEEK (A + 1) 200  POKE 237, PEEK (A + 2) 210  POKE 238, PEEK (A) 220  POKE 239,0 230  FOR I = 250 TO 253 240  POKE I,0 250  NEXT 260  CALL 37230 270  FOR I = 253 TO 250 STEP  - 1 280 B =  PEEK (I) 290  FOR J = 0 TO 1 300  PRINT  MID$ ("0123456789ABCDEF",B / 16 + 1,1); 310 B = (B -  INT (B / 16) * 16) * 16 320  NEXT J,I

AutoHotkey

DllCall / WinAPI

CRC32(str,enc="UTF-8"){l:=(enc="CP1200"||enc="UTF-16")?2:1,s:=(StrPut(str,enc)-1)*lVarSetCapacity(b,s,0)&&StrPut(str,&b,floor(s/l),enc)CRC32:=DllCall("ntdll.dll\RtlComputeCrc32","UInt",0,"Ptr",&b,"UInt",s)returnFormat("{:#x}",CRC32)}MsgBox%CRC32("The quick brown fox jumps over the lazy dog")
Output:
0x414fa339

Implementation

CRC32(str){statictable:=[]loop256{crc:=A_Index-1loop8crc:=(crc&1)?(crc>>1)^0xEDB88320:(crc>>1)table[A_Index-1]:=crc}crc:=~0loop,parse,strcrc:=table[(crc&0xFF)^Asc(A_LoopField)]^(crc>>8)returnFormat("{:#x}",~crc)}MsgBox%CRC32("The quick brown fox jumps over the lazy dog")
Output:
0x414fa339

Bait

import hash.crc32fun main() {text := 'The quick brown fox jumps over the lazy dog'sum := crc32.checksum(text.bytes())println(sum.hex())}
Output:
414fa339

C

Library

Usingzlib's crc32:

#include<stdio.h>#include<string.h>#include<zlib.h>intmain(){constchar*s="The quick brown fox jumps over the lazy dog";printf("%lX\n",crc32(0,(constvoid*)s,strlen(s)));return0;}

Implementation

This code is a translation fromRuby, with an adjustment to use 32-bit integers. This code happens to resemble the examples fromRFC 1952 section 8 and fromPNG annex D, because those examples use an identical table.

#include<inttypes.h>#include<stdio.h>#include<string.h>uint32_trc_crc32(uint32_tcrc,constchar*buf,size_tlen){staticuint32_ttable[256];staticinthave_table=0;uint32_trem;uint8_toctet;inti,j;constchar*p,*q;/* This check is not thread safe; there is no mutex. */if(have_table==0){/* Calculate CRC table. */for(i=0;i<256;i++){rem=i;/* remainder from polynomial division */for(j=0;j<8;j++){if(rem&1){rem>>=1;rem^=0xedb88320;}elserem>>=1;}table[i]=rem;}have_table=1;}crc=~crc;q=buf+len;for(p=buf;p<q;p++){octet=*p;/* Cast to unsigned octet. */crc=(crc>>8)^table[(crc&0xff)^octet];}return~crc;}intmain(){constchar*s="The quick brown fox jumps over the lazy dog";printf("%"PRIX32"\n",rc_crc32(0,s,strlen(s)));return0;}

C#

/// <summary>/// Performs 32-bit reversed cyclic redundancy checks./// </summary>publicclassCrc32{#region Constants/// <summary>/// Generator polynomial (modulo 2) for the reversed CRC32 algorithm./// </summary>privateconstUInt32s_generator=0xEDB88320;#endregion#region Constructors/// <summary>/// Creates a new instance of the Crc32 class./// </summary>publicCrc32(){// Constructs the checksum lookup table. Used to optimize the checksum.m_checksumTable=Enumerable.Range(0,256).Select(i=>{vartableEntry=(uint)i;for(varj=0;j<8;++j){tableEntry=((tableEntry&1)!=0)?(s_generator^(tableEntry>>1)):(tableEntry>>1);}returntableEntry;}).ToArray();}#endregion#region Methods/// <summary>/// Calculates the checksum of the byte stream./// </summary>/// <param name="byteStream">The byte stream to calculate the checksum for.</param>/// <returns>A 32-bit reversed checksum.</returns>publicUInt32Get<T>(IEnumerable<T>byteStream){try{// Initialize checksumRegister to 0xFFFFFFFF and calculate the checksum.return~byteStream.Aggregate(0xFFFFFFFF,(checksumRegister,currentByte)=>(m_checksumTable[(checksumRegister&0xFF)^Convert.ToByte(currentByte)]^(checksumRegister>>8)));}catch(FormatExceptione){thrownewCrcException("Could not read the stream out as bytes.",e);}catch(InvalidCastExceptione){thrownewCrcException("Could not read the stream out as bytes.",e);}catch(OverflowExceptione){thrownewCrcException("Could not read the stream out as bytes.",e);}}#endregion#region Fields/// <summary>/// Contains a cache of calculated checksum chunks./// </summary>privatereadonlyUInt32[]m_checksumTable;#endregion}

Test:

vararrayOfBytes=Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog");varcrc32=newCrc32();Console.WriteLine(crc32.Get(arrayOfBytes).ToString("X"));
Output:

414fa339

C++

#include<array>#include<ranges>#include<cstdint>#include<numeric>#include<concepts>#include<algorithm>// These headers are only needed for main(), to demonstrate.#include<iomanip>#include<iostream>#include<string_view>inlineconstexprautocrc_table=[](){std::array<std::uint32_t,256>retval{};std::generate(retval.begin(),retval.end(),[n=std::uint32_t{0}]()mutable{autoc=n++;for(std::uint8_tk=0;k<8;++k){if(c&1)c=std::uint32_t{0xedb88320}^(c>>1);elsec>>=1;}returnc;});returnretval;}();[[nodiscard]]constexprstd::uint32_tcrc(conststd::ranges::input_rangeauto&rng)noexceptrequiresstd::convertible_to<std::ranges::range_value_t<decltype(rng)>,std::uint8_t>{return~std::accumulate(std::ranges::begin(rng),std::ranges::end(rng),~std::uint32_t{0}&std::uint32_t{0xff'ff'ff'ffu},[](std::uint32_tchecksum,std::uint8_tvalue){returncrc_table[(checksum^value)&0xff]^(checksum>>8);});}intmain(){constexprstd::string_viewstr="The quick brown fox jumps over the lazy dog";std::cout<<std::hex<<std::setw(8)<<std::setfill('0')<<crc(str)<<'\n';}
Output:
414fa339
"The quick brown fox jumps over the lazy dog"(to hex ...)54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F67 414FA339[other useful test vectors]0000000000000000000000000000000000000000000000000000000000000000 190A55ADFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FF6CAB0B000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F 91267E8A
Library:boost
#include<boost\crc.hpp>#include<string>#include<iostream>intmain(){std::stringstr("The quick brown fox jumps over the lazy dog");boost::crc_32_typecrc;crc.process_bytes(str.data(),str.size());std::cout<<"Checksum: "<<std::hex<<crc.checksum()<<std::endl;return0;}
Output:
Checksum: 414fa339

Clojure

Translation of:Java
(let[crc(newjava.util.zip.CRC32)str"The quick brown fox jumps over the lazy dog"](.crcupdate(.strgetBytes))(printf"CRC-32('%s') = %s\n"str(Long/toHexString(.crcgetValue))))
Output:
CRC-32('The quick brown fox jumps over the lazy dog') = 414fa339

COBOL

Works with:GnuCOBOL
Library:zlib
      *> tectonics: cobc -xj crc32-zlib.cob -lzidentificationdivision.program-id.rosetta-crc32.environmentdivision.configurationsection.repository.functionallintrinsic.datadivision.working-storagesection.01crc32-initialusagebinary-c-long.01crc32-resultusagebinary-c-longunsigned.01crc32-input.05value"The quick brown fox jumps over the lazy dog".01crc32-hexusagepointer.proceduredivision.crc32-main.      *> libz crc32call"crc32"usingbyvaluecrc32-initialbyreferencecrc32-inputbyvaluelength(crc32-input)returningcrc32-resultonexceptiondisplay"error: no crc32 zlib linkage"uponsyserrend-callcall"printf"using"checksum: %lx"&x"0a"byvaluecrc32-result      *> GnuCOBOL pointers are displayed in hex by defaultsetcrc32-hexupbycrc32-resultdisplay'crc32 of "'crc32-input'" is 'crc32-hexgoback.endprogramrosetta-crc32.
Output:
prompt$ cobc -xj crc32-zlib.cob -lzchecksum: 414fa339crc32 of "The quick brown fox jumps over the lazy dog" is 0x00000000414fa339

CoffeeScript

Allows the specification of the initial CRC value, which defaults to 0xFFFFFFFF. Optimized for speed and terseness (then readability/indentation).

crc32=do->table=fornin[0..255]for[0..7]ifn&1n=0xEDB88320^n>>>1elsen>>>=1n(str, crc = -1) ->forcinstrcrc=crc>>>8^table[(crc^c.charCodeAt0)&255](crc^-1)>>>0

Test:

console.log(crc32'The quick brown fox jumps over the lazy dog').toString16

Output:

414fa339

Common Lisp

Library:Ironclad
(ql:quickload:ironclad)(defunstring-to-digest(strdigest)"Return the specified digest for the ASCII string as a hex string."(ironclad:byte-array-to-hex-string(ironclad:digest-sequencedigest(ironclad:ascii-string-to-byte-arraystr))))(string-to-digest"The quick brown fox jumps over the lazy dog":crc32)
Output:
"414fa339"

Component Pascal

BlackBox Component Builder
Require ZLib Subsystem

MODULEBbtComputeCRC32;IMPORTZlibCrc32,StdLog;PROCEDUREDo*;VARs:ARRAY128OFSHORTCHAR;BEGINs:="The quick brown fox jumps over the lazy dog";StdLog.IntForm(ZlibCrc32.CRC32(0,s,0,LEN(s$)),16,12,'0',TRUE);StdLog.Ln;ENDDo;ENDBbtComputeCRC32.

Execute: ^Q BbtComputeCRC32.Do

Output:
0414FA339%16

Crystal

require"digest/crc32";pDigest::CRC32.checksum("The quick brown fox jumps over the lazy dog").to_s(16)
Output:
"414fa339"

D

voidmain(){importstd.stdio,std.digest.crc;"The quick brown fox jumps over the lazy dog".crc32Of.crcHexString.writeln;}
Output:
414FA339

Delphi

programCalcCRC32;{$APPTYPE CONSOLE}usesSystem.SysUtils,System.ZLib;varData:AnsiString='The quick brown fox jumps over the lazy dog';CRC:UInt32;beginCRC:=crc32(0,@Data[1],Length(Data));WriteLn(Format('CRC32 = %8.8X',[CRC]));end.
Output:
CRC32 = 414FA339

EasyLang

func crc32 buf$[] .   for i = 0 to 0xff      rem = i      for j to 8         if bitand rem 1 = 1            rem = bitxor bitshift rem -1 0xedb88320         else            rem = bitshift rem -1         .      .      table[] &= rem   .   crc = 0xffffffff   for c$ in buf$[]      c = strcode c$      crb = bitxor bitand crc 0xff c      crc = bitxor (bitshift crc -8) table[crb + 1]   .   return bitnot crc.s$ = "The quick brown fox jumps over the lazy dog"print crc32 strchars s$
Output:
1095738169

Elixir

defmoduleTestdodefcrc32(str)doIO.puts:erlang.crc32(str)|>Integer.to_string(16)endendTest.crc32("The quick brown fox jumps over the lazy dog")
Output:
414FA339

Erlang

Using the built-in crc32 implementation.

-module(crc32).-export([test/0]).test()->io:fwrite("~.16#~n",[erlang:crc32(<<"The quick brown fox jumps over the lazy dog">>)]).
Output:
16#414FA339

F#

moduleCrc32=openSystem// Generator polynomial (modulo 2) for the reversed CRC32 algorithm.letprivates_generator=uint320xEDB88320// Generate lookup tableletprivatelutIntermediateinput=if(input&&&uint321)<>uint320thens_generator^^^(input>>>1)elseinput>>>1letprivatelutEntryinput={0..7}|>Seq.fold(funaccx->lutIntermediateacc)inputletprivatecrc32lut=[uint320..uint320xFF]|>List.maplutEntryletcrc32byte(register:uint32)(byte:byte)=crc32lut.[Convert.ToInt32((register&&&uint320xFF)^^^Convert.ToUInt32(byte))]^^^(register>>>8)// CRC32 of a byte arrayletcrc32(input:byte[])=letresult=Array.foldcrc32byte(uint320xFFFFFFFF)input~~~result// CRC32 from ASCII stringletcrc32OfAscii(inputAscii:string)=letbytes=System.Text.Encoding.ASCII.GetBytes(inputAscii)crc32bytes// TestlettestString="The quick brown fox jumps over the lazy dog"printfn"ASCII Input: %s"testStringletresult=crc32OfAsciitestStringprintfn"CRC32: 0x%x"result
Output:
ASCIIInput:ThequickbrownfoxjumpsoverthelazydogCRC32:0x414fa339

Factor

LikeSHA-1#Factor, but with crc32.

IN: scratchpadUSING: checksums checksums.crc32 ;IN: scratchpad"The quick brown fox jumps over the lazy dog" crc32checksum-bytes hex-string ."414fa339"

The implementation is atcore/checksums/crc32/crc32.factor.

FBSL

#APPTYPECONSOLEPRINTHEX(CHECKSUM("The quick brown fox jumps over the lazy dog"))PAUSE
Output:
414FA339Press any key to continue...

Forth

This code can implement other types of CRC by using other polynomial constants: use $8408 for CCITT CRC-16, or $a001 for IBM CRC-16.

:crc/( n -- n )80dodup1rshiftswap1andif$edb88320xorthenloop;:crcfill2560doicrc/,loop;createcrctblcrcfill:crc+( crc n -- crc' )overxor$ffandcellscrctbl+@swap8rshiftxor;:crcbuf( crc str len -- crc )bounds?doic@crc+loop;$ffffffffs"The quick brown fox jumps over the lazy dog"crcbuf$ffffffffxorhex.bye\ $414FA339

Fortran

modulecrc32_museiso_fortran_envimplicit noneinteger(int32)::crc_table(0:255)contains    subroutineupdate_crc(a,crc)integer::n,icharacter(*)::ainteger(int32)::crccrc=not(crc)n=len(a)doi=1,ncrc=ieor(shiftr(crc,8),crc_table(iand(ieor(crc,iachar(a(i:i))),255)))end docrc=not(crc)end subroutine    subroutineinit_tableinteger::i,jinteger(int32)::kdoi=0,255k=idoj=1,8if(btest(k,0))thenk=ieor(shiftr(k,1),-306674912)elsek=shiftr(k,1)end if            end docrc_table(i)=kend do    end subroutineend moduleprogramcrc32usecrc32_mimplicit noneinteger(int32)::crc=0character(*),parameter::s="The quick brown fox jumps over the lazy dog"callinit_tablecallupdate_crc(s,crc)print"(Z8)",crcend program

FreeBASIC

Translation of:C
' version 18-03-2017' compile with: fbc -s consoleFunctioncrc32(bufAsString)AsUInteger<32>StaticAsUInteger<32>table(256)StaticAsUInteger<32>have_tableDimAsUInteger<32>crc,kDimAsULongi,jIfhave_table=0ThenFori=0To255k=iForj=0To7If(kAnd1)ThenkShr=1kXor=&Hedb88320ElsekShr=1EndIftable(i)=kNextNexthave_table=1EndIfcrc=Notcrc' crc = &HffffffffFori=0ToLen(buf)-1crc=(crcShr8)Xortable((crcAnd&hff)Xorbuf[i])NextReturnNotcrcEndFunction' ------=< MAIN >=------DimAsStringl="The quick brown fox jumps over the lazy dog"DimAsUInteger<32>crcPrint"input = ";lprintPrint"The CRC-32 checksum = ";Hex(crc32(l),8)' empty keyboard bufferWhileInkey<>"":WendPrint:Print"hit any key to end program"SleepEnd
Output:
input = The quick brown fox jumps over the lazy dogThe CRC-32 checksum = 414FA339

Go

Library

packagemainimport("fmt""hash/crc32")funcmain(){s:=[]byte("The quick brown fox jumps over the lazy dog")result:=crc32.ChecksumIEEE(s)fmt.Printf("%X\n",result)}
Output:
414FA339

Implementation

packagemainimport"fmt"vartable[256]uint32funcinit(){fori:=rangetable{word:=uint32(i)forj:=0;j<8;j++{ifword&1==1{word=(word>>1)^0xedb88320}else{word>>=1}}table[i]=word}}funccrc32(sstring)uint32{crc:=^uint32(0)fori:=0;i<len(s);i++{crc=table[byte(crc)^s[i]]^(crc>>8)}return^crc}funcmain(){fmt.Printf("%0x\n",crc32("The quick brown fox jumps over the lazy dog"))}
Output:
414fa339

Groovy

defcrc32(byte[]bytes){newjava.util.zip.CRC32().with{updatebytes;value}}

Testing:

assert'414FA339'==sprintf('%04X',crc32('The quick brown fox jumps over the lazy dog'.bytes))

Haskell

Pure Haskell:

importData.Bits((.&.),complement,shiftR,xor)importData.Word(Word32)importNumeric(showHex)crcTable::Word32->Word32crcTable=(table!!).fromIntegralwheretable=((!!8).iteratexf)<$>[0..255]shiftedx=shiftRx1xfr|r.&.1==1=xor(shiftedr)0xedb88320|otherwise=shiftedrcharToWord::Char->Word32charToWord=fromIntegral.fromEnumcalcCrc::String->Word32calcCrc=complement.foldlcf(complement0)wherecfcrcx=xor(shiftRcrc8)(crcTable$xor(crc.&.0xff)(charToWordx))crc32::String->Stringcrc32=flipshowHex[].calcCrcmain::IO()main=putStrLn$crc32"The quick brown fox jumps over the lazy dog"
Output:
414fa339


Using the zlib C library ( compile with "ghc -lz file.hs"):

importData.List(genericLength)importNumeric(showHex)importForeign.Cforeignimportccall"zlib.h crc32"zlib_crc32::CULong->CString->CUInt->CULongmain::IO()main=dolets="The quick brown fox jumps over the lazy dog"ptr<-newCStringsletr=zlib_crc320ptr(genericLengths)putStrLn$showHexr""
Output:
414fa339

Haxe

usingStringTools;classMain{staticfunctionmain(){vardata=haxe.io.Bytes.ofString("The quick brown fox jumps over the lazy dog");varcrc=haxe.crypto.Crc32.make(data);Sys.println(crc.hex());}}
Output:
414FA339

Icon andUnicon

There is no library function for this so we implement one. Icon/Unicon binary operations apply to large integers so we need to mask to the desired unsigned word size. This also only applies to full bytes.

linkhexcvt,printfproceduremain()s:="The quick brown fox jumps over the lazy dog"a:="414FA339"printf("crc(%i)=%s - implementation is %s\n",s,r:=crc32(s),ifr==athen"correct"else"in error")endprocedurecrc32(s)#: return crc-32 (ISO 3309, ITU-T V.42, Gzip, PNG) of sstaticcrcL,maskinitial{crcL:=list(256)# crc tablep:=[0,1,2,4,5,7,8,10,11,12,16,22,23,26]# polynomial termsmask:=2^32-1# word size maskevery(poly:=0):=ior(poly,ishift(1,31-p[1to*p]))everyc:=n:=0to*crcL-1do{# tableevery1to8doc:=iand(mask,ifiand(c,1)=1thenixor(poly,ishift(c,-1))elseishift(c,-1))crcL[n+1]:=c}}crc:=ixor(0,mask)# invert bitseverycrc:=iand(mask,ixor(crcL[iand(255,ixor(crc,ord(!s)))+1],ishift(crc,-8)))returnhexstring(ixor(crc,mask))# return hexstringend
Library:Icon Programming Library

hexcvt.icn (provides hex and hexstring)printf.icn (provides formatting)

Output:
crc("The quick brown fox jumps over the lazy dog")=414FA339 - implementation is correct

J

((i.32)e.32262322161211108754210)128!:3'The quick brown fox jumps over the lazy dog'_3199229127

Other possible representations of this result:

(2^32x)|((i.32)e.32262322161211108754210)128!:3'The quick brown fox jumps over the lazy dog'1095738169require'convert'hfd(2^32x)|((i.32)e.32262322161211108754210)128!:3'The quick brown fox jumps over the lazy dog'414FA339

Java

importjava.util.zip.CRC32;
publicstaticvoidmain(String[]args)throwsIOException{Stringstring="The quick brown fox jumps over the lazy dog";CRC32crc=newCRC32();crc.update(string.getBytes());System.out.printf("%x",crc.getValue());}
Output:
414fa339

JavaScript

(()=>{'use strict';// --------------------- CRC-32 ----------------------// crc32 :: String -> Intconstcrc32=str=>{// table :: [Int]consttable=enumFromTo(0)(255).map(n=>take(9)(iterate(x=>(x&1?(z=>0xEDB88320^z):identity)(x>>>1))(n))[8]);returnchars(str).reduce((a,c)=>(a>>>8)^table[(a^c.charCodeAt(0))&255],-1)^-1;};// ---------------------- TEST -----------------------// main :: IO ()constmain=()=>showHex(crc32('The quick brown fox jumps over the lazy dog'));// --------------------- GENERIC ---------------------// chars :: String -> [Char]constchars=s=>s.split('');// enumFromTo :: Int -> Int -> [Int]constenumFromTo=m=>n=>!isNaN(m)?(Array.from({length:1+n-m},(_,i)=>m+i)):enumFromTo_(m)(n);// identity :: a -> aconstidentity=x=>// The identity function.x;// iterate :: (a -> a) -> a -> Gen [a]constiterate=f=>// An infinite list of repeated// applications of f to x.function*(x){letv=x;while(true){yield(v);v=f(v);}};// showHex :: Int -> StringconstshowHex=n=>// Hexadecimal string for a given integer.'0x'+n.toString(16);// take :: Int -> [a] -> [a]// take :: Int -> String -> Stringconsttake=n=>// The first n elements of a list,// string of characters, or stream.xs=>'GeneratorFunction'!==xs.constructor.constructor.name?(xs.slice(0,n)):[].concat.apply([],Array.from({length:n},()=>{constx=xs.next();returnx.done?[]:[x.value];}));// MAIN -------------constresult=main();return(console.log(result),result);})();
Output:
0x414fa339

Jsish

From the shell

#Util.crc32('The quick brown fox jumps over the lazy dog').toString(16);
Output:
"414fa339"

jq

Adapted fromWren

Works with jq, the C implementation of jq

Works with gojq, the Go implementation of jq

The following program will also work with jaq, the Rust implementationof jq, provided the relevant functions of the "bitwise" moduleare included in place of the "include" directive, and thatthe definition of `div` is modified to read as follows:

def div($j):  ((. - (. % $j)) / $j) | round;
include "bitwise" {search: "."};  # see above# non-negative decimal integer to hex stringdef hex:  def stream:    recurse(if . >= 16 then ./16|floor else empty end) | . % 16 ;  [stream] | reverse  |  map(if . < 10 then 48 + . else . + 87 end) | implode ;### CRC-32def crc32Table:  reduce range(0; 256) as $i ([];    . + [reduce range(0; 8) as $j ($i;              if bitwise_and(.;1) == 1              then bitwise_xor(rightshift(1); 3988292384) # 0xedb88320              else rightshift( 1 )              end) ] );# Input: an ASCII string# Output: its CRC-32def crc32:  explode as $s  | crc32Table as $table  | reduce range(0; $s|length) as $i (4294967295 ; # ~0      # 0xff is 255      bitwise_and(.; 255 ) as $crb      | bitwise_xor( $table[bitwise_xor($crb; $s[$i])] ; rightshift(8)) )  | flip(32) ;def task:  crc32 | hex;"The quick brown fox jumps over the lazy dog" | task
Output:
414fa339

Julia

Using the zlib Library

usingLibzprintln(string(Libz.crc32(UInt8.(b"The quick brown fox jumps over the lazy dog")),base=16))
Output:
414fa339

Source Implementation

Works with:Julia version 0.6
functioncrc32(crc::Int,str::String)table=zeros(UInt32,256)foriin0:255tmp=iforjin0:7iftmp&1==1tmp>>=1tmp⊻=0xedb88320elsetmp>>=1endendtable[i+1]=tmpendcrc⊻=0xffffffffforiinUInt32.(collect(str))crc=(crc>>8)table[(crc&0xff)i+1]endcrc0xffffffffendstr="The quick brown fox jumps over the lazy dog"crc=crc32(0,str)assert(crc==0x414fa339)println("Message: ",str)println("Checksum: ",hex(crc))
Output:
Message: The quick brown fox jumps over the lazy dogChecksum: 414fa339

Kotlin

// version 1.0.6importjava.util.zip.CRC32funmain(args:Array<String>){valtext="The quick brown fox jumps over the lazy dog"valcrc=CRC32()with(crc){update(text.toByteArray())println("The CRC-32 checksum of '$text' = ${"%x".format(value)}")}}
Output:
The CRC-32 checksum of 'The quick brown fox jumps over the lazy dog' = 414fa339

Lingo

Pure Lingo

crcObj = script("CRC").new()crc32 = crcObj.crc32("The quick brown fox jumps over the lazy dog")put crc32-- <ByteArrayObject length = 4 ByteArray = 0x41, 0x4f, 0xa3, 0x39 >put crc32.toHexString(1, crc32.length)-- "41 4f a3 39"

Implementation:

--****************************************************************************-- @desc      CRC-32 Class-- @file      parent script "CRC"-- @version   0.1--****************************************************************************property _CRC32Table------------------------------------------ @constructor----------------------------------------on new me  -- used for fast CRC32 calculation  me._CRC32Table = [\  0, 1996959894, -301047508, -1727442502, 124634137, 1886057615, -379345611, -1637575261, 249268274, 2044508324,\  -522852066, -1747789432, 162941995, 2125561021, -407360249, -1866523247, 498536548, 1789927666, -205950648,\  -2067906082, 450548861, 1843258603, -187386543, -2083289657, 325883990, 1684777152, -43845254, -1973040660,\  335633487, 1661365465, -99664541, -1928851979, 997073096, 1281953886, -715111964, -1570279054, 1006888145,\  1258607687, -770865667, -1526024853, 901097722, 1119000684, -608450090, -1396901568, 853044451, 1172266101,\  -589951537, -1412350631, 651767980, 1373503546, -925412992, -1076862698, 565507253, 1454621731, -809855591,\  -1195530993, 671266974, 1594198024, -972236366, -1324619484, 795835527, 1483230225, -1050600021, -1234817731,\  1994146192, 31158534, -1731059524, -271249366, 1907459465, 112637215, -1614814043, -390540237, 2013776290,\  251722036, -1777751922, -519137256, 2137656763, 141376813, -1855689577, -429695999, 1802195444, 476864866,\  -2056965928, -228458418, 1812370925, 453092731, -2113342271, -183516073, 1706088902, 314042704, -1950435094,\  -54949764, 1658658271, 366619977, -1932296973, -69972891, 1303535960, 984961486, -1547960204, -725929758,\  1256170817, 1037604311, -1529756563, -740887301, 1131014506, 879679996, -1385723834, -631195440, 1141124467,\  855842277, -1442165665, -586318647, 1342533948, 654459306, -1106571248, -921952122, 1466479909, 544179635,\  -1184443383, -832445281, 1591671054, 702138776, -1328506846, -942167884, 1504918807, 783551873, -1212326853,\  -1061524307, -306674912, -1698712650, 62317068, 1957810842, -355121351, -1647151185, 81470997, 1943803523,\  -480048366, -1805370492, 225274430, 2053790376, -468791541, -1828061283, 167816743, 2097651377, -267414716,\  -2029476910, 503444072, 1762050814, -144550051, -2140837941, 426522225, 1852507879, -19653770, -1982649376,\  282753626, 1742555852, -105259153, -1900089351, 397917763, 1622183637, -690576408, -1580100738, 953729732,\  1340076626, -776247311, -1497606297, 1068828381, 1219638859, -670225446, -1358292148, 906185462, 1090812512,\  -547295293, -1469587627, 829329135, 1181335161, -882789492, -1134132454, 628085408, 1382605366, -871598187,\  -1156888829, 570562233, 1426400815, -977650754, -1296233688, 733239954, 1555261956, -1026031705, -1244606671,\  752459403, 1541320221, -1687895376, -328994266, 1969922972, 40735498, -1677130071, -351390145, 1913087877,\  83908371, -1782625662, -491226604, 2075208622, 213261112, -1831694693, -438977011, 2094854071, 198958881,\  -2032938284, -237706686, 1759359992, 534414190, -2118248755, -155638181, 1873836001, 414664567, -2012718362,\  -15766928, 1711684554, 285281116, -1889165569, -127750551, 1634467795, 376229701, -1609899400, -686959890,\  1308918612, 956543938, -1486412191, -799009033, 1231636301, 1047427035, -1362007478, -640263460, 1088359270,\  936918000, -1447252397, -558129467, 1202900863, 817233897, -1111625188, -893730166, 1404277552, 615818150,\  -1160759803, -841546093, 1423857449, 601450431, -1285129682, -1000256840, 1567103746, 711928724, -1274298825,\  -1022587231, 1510334235, 755167117]  return meend------------------------------------------ Calculates CRC-32 checksum of string or bytearray-- @param {bytearray|string} input-- @return {bytearray} (4 bytes)----------------------------------------on crc32 (me, input)  if stringP(input) then input = bytearray(input)  crc = -1  len = input.length  repeat with i = 1 to len    if (crc>0) then bitShift8 = crc/256    else bitShift8 = bitAnd(crc,2147483647)/256+8388608    crc = bitXor(bitShift8,me._CRC32Table[bitAnd(bitXor(crc,input[i]),255)+1])  end repeat  ba = bytearray()  ba.endian = #bigEndian  ba.writeInt32(bitXOr(crc,-1))  ba.position = 1  return baend

Using an "Xtra" (=binary plugin)

cx = Xtra("Crypto").new()put cx.cx_crc32_string("The quick brown fox jumps over the lazy dog")-- "414fa339"

Lua

Using Library

zlib.crc32

localcompute=require"zlib".crc32()localsum=compute("The quick brown fox jumps over the lazy dog")print(string.format("0x%x",sum))
Output:

0x414fa339

Implementation

functioncrc32(buf,size)localcrc=0xFFFFFFFFlocaltable={}localrem,c-- calculate CRC-tablefori=0,0xFFdorem=iforj=1,8doif(rem&1==1)thenrem=rem>>1rem=rem~0xEDB88320elserem=rem>>1endendtable[i]=remendforx=1,sizedoc=buf[x]crc=(crc>>8)~table[(crc&0xFF)~c]endreturncrc~0xFFFFFFFFendlocalstr="The quick brown fox jumps over the lazy dog"localt={}fori=1,#strdot[i]=str:byte(i)endprint(string.format("CRC32: %x",crc32(t,#str)))
Output:

CRC32: 414fa339

M2000 Interpreter

Using Code

oduleCheckIt{crc32=lambda->{FunctionPrepareTable{buffertaslong*256Fori=0To255k=iForj=0To7Ifbinary.and(k,1)=1Thenk=binary.Xor(binary.shift(k,-1),0xEDB88320)Elsek=binary.shift(k,-1)EndIfNextReturnt,i:=kNext=t}=lambdacrctable=PrepareTable()(c,buf$)->{crc=0xFFFFFFFF-cFori=1ToLen(buf$)crc=binary.xor(binary.shift(crc,-8),eval(crctable,binary.xor(binary.and(crc,0xff),asc(mid$(buf$,i,1)))))Nexti=0xFFFFFFFF-crc}}()' execute  nowPrintcrc32(0,"The quick brown fox jumps over the lazy dog")=0x414fa339&Printcrc32(crc32(0,"The quick brown fox jumps")," over the lazy dog")=0x414fa339&Printcrc32(crc32(crc32(0,"The qu"),"ick brown")," fox jumps over the lazy dog")=0x414fa339&}CheckIt

Using Api

ModuleCheckApi{DeclareCRC32LIB"ntdll.RtlComputeCrc32"{LongZero,a$,longs}a$=Str$("The quick brown fox jumps over the lazy dog")l=len(a$)*2HexUint(CRC32(0,a$,l))}CheckApi

Mathematica /Wolfram Language

type="CRC32";(*pick one out of 13 predefined hash types*)StringForm["The "<>type<>" hash code of \"``\" is ``.",s="The quick brown fox jumps over the lazy dog",Hash[s,type,"HexString"]]
Output:
The CRC32 hash code of "The quick brown fox jumps over the lazy dog" is 414fa339.

Neko

The NekoVM is a 31 bit machine; 30 signed. Loadable primitives handle 32bit integers. The zlib library API exposes a CRC-32 function, that expects and returns Int32.

/** <doc>CRC32 in Neko</doc>**/varint32_new=$loader.loadprim("std@int32_new",1)varupdate_crc32=$loader.loadprim("zlib@update_crc32",4)varcrc=int32_new(0)vartxt="The quick brown fox jumps over the lazy dog"crc=update_crc32(crc,txt,0,$ssize(txt))$print(crc,"\n")
Output:
prompt$ nekoc crc32.nekoprompt$ neko crc32.n1095738169prompt$ dc -e "$(neko crc32.n) 16op"414FA339

NetRexx

Translation of:Java
/* NetRexx */optionsreplaceformatcommentsjavacrossrefsymbolsbinaryimportjava.util.zip.CRC32toBeEncoded=String("The quick brown fox jumps over the lazy dog")myCRC=CRC32()myCRC.update(toBeEncoded.getBytes())say"The CRC-32 value is :"Long.toHexString(myCRC.getValue())"!"return
Output:
The CRC-32 value is : 414fa339 !

Nim

importstrutilstypeTCrc32*=uint32constInitCrc32*=TCrc32(0xffffffff)proccreateCrcTable():array[0..255,TCrc32]=foriin0..255:varrem=TCrc32(i)forjin0..7:if(remand1)>0:rem=(remshr1)xorTCrc32(0xedb88320)else:rem=remshr1result[i]=rem# Table created at compile timeconstcrc32table=createCrcTable()proccrc32(s:string):TCrc32=result=InitCrc32forcins:result=(resultshr8)xorcrc32table[(resultand0xff)xorbyte(c)]result=notresultechocrc32("The quick brown fox jumps over the lazy dog").int64.toHex(8)
Output:
414FA339

NOWUT

adapted from FreeBASIC

; link with PIOxxx.OBJ        sectionbsscrctable.d:     resd 256        sectiondatahavetable.b:    db 0string:         db "The quick brown fox jumps over the lazy dog"stringend:                      db 13,10,0        ; carriage return and null terminator                        sectioncodestart!        gosub initplatform        beginfunc        localvar crc.d        callex ,printnt,"input = ".a        callex ,printnt,string        callex ,printnt,"The CRC-32 checksum = ".a        callex crc,crc32,string,stringend        callex ,printhexr,crc        endfunc        endcrc32:        beginfunc bufend.d,buf.d        localvar i.d,j.d,k.d,k2.d,crc.d        ifunequal havetable,0,tabledone        i=0        whileless i,256        k=i > j=8        countdown j        k2=k > k=_ shr 1        ifequal k2 and 1,0,noxor > k=_ xor $EDB88320noxor:        nextcount        crctable(i shl 2)=k        i=_+1        wend        havetable=1tabledone:        crc=-1                whileless buf,bufend        crc=_ shr 8 xor crctable(crc and $FF xor [buf].b shl 2)        buf=_+1        wend        crc=_ xor -1        endfunc crc        returnex 8                        ; clean off 2 parameters from the stack
Output:
input = The quick brown fox jumps over the lazy dogThe CRC-32 checksum = 414FA339

Oberon-2

Works with:oo2c Version 2
MODULECRC32;IMPORTNPCT:Zlib,Strings,Out;VARs:ARRAY128OFCHAR;BEGINCOPY("The quick brown fox jumps over the lazy dog",s);Out.Hex(Zlib.CRC32(0,s,0,Strings.Length(s)),0);Out.LnENDCRC32.
Output:
414FA339

Objeck

class CRC32 {  function : Main(args : String[]) ~ Nil {    "The quick brown fox jumps over the lazy dog"->ToByteArray()->CRC32()->PrintLine();  }}
Output:
1095738169

OCaml

Library:camlzip
let()=lets="The quick brown fox jumps over the lazy dog"inletcrc=Zlib.update_crc0ls0(String.lengths)inPrintf.printf"crc: %lX\n"crc

Running this code in interpreted mode:[[Media:Insert non-formatted text here]][[File:[Example.jpg][http://www.example.com link title]]]

$ ocaml unix.cma -I +zip zip.cma crc.mlcrc: 414FA339

Ol

(define(crc32str)(bxor#xFFFFFFFF(fold(lambda(crcchar)(letloop((n8)(crccrc)(bitschar))(if(eq?n0)crc(let*((flag(band(bxorbitscrc)1))(crc(>>crc1))(crc(if(eq?flag0)crc(bxorcrc#xEDB88320)))(bits(>>bits1)))(loop(-n1)crcbits)))))#xFFFFFFFF(string->liststr))))(print(number->string(crc32"The quick brown fox jumps over the lazy dog")16))(print(number->string(crc32(list->string(repeat#x0032)))16))(print(number->string(crc32(list->string(repeat#xFF32)))16))(print(number->string(crc32(list->string(iota32)))16))
Output:
414fa339190a55adff6cab0b91267e8a

ooRexx

This Program shows how easy it is to use JAVA functionality from ooRexx.bsf4oorexx from Sourceforgehttps://sourceforge.net/projects/bsf4oorexx/ makes that possible.

/* ooRexx */clzCRC32=bsf.importClass("java.util.zip.CRC32")myCRC32=clzCRC32~newtoBeEncoded="The quick brown fox jumps over the lazy dog"myCRC32~update(BsfRawBytes(toBeEncoded))numericdigits20say'The CRC-32 value of "'toBeEncoded'" is:'myCRC32~getValue~d2x::requires"BSF.CLS"--getJavabridge
Output:
The CRC-32 value of "The quick brown fox jumps over the lazy dog" is: 414FA339

PARI/GP

Using Linux system library (Linux only solution)

Library:libz.so
install("crc32", "lLsL", "crc32", "libz.so");s = "The quick brown fox jumps over the lazy dog";printf("%0x\n", crc32(0, s, #s))

Output:

414fa339

Pascal

Free Pascal

ProgramCheckCRC;{$IFDEF fpc}{$mode Delphi}{$ENDIF}{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}usessysutils,crc;functionCrcString(constmystring:string):longword;varcrcvalue:longword;begincrcvalue:=crc32(0,nil,0);result:=crc32(crcvalue,@mystring[1],length(mystring));end;varmytext:string;beginmyText:='The quick brown fox jumps over the lazy dog';writeln('crc32 = ',IntToHex(CrcString(mytext),8));end.

Output:

crc32 = 414FA339

PascalABC.NET

typeTCrc32=array[0..255]oflongword;functionCreateCrcTable():TCrc32;beginforvari:longword:=0to255dobeginvarrem:=i;forvarj:=0to7doif(remand1)>0thenrem:=(remshr1)xor$edb88320elserem:=remshr1;result[i]:=remend;end;constCrc32Table=CreateCrcTable;functionCrc32(s:string):longword;beginresult:=$ffffffff;foreachvarcinsdoresult:=(resultshr8)xorCrc32Table[(resultand$ff)xorbyte(c)];result:=notresultend;beginwriteln('crc32 = ',crc32('The quick brown fox jumps over the lazy dog').ToString('X'));end.
Output:
crc32 = 414FA339

Perl

#!/usr/bin/perluse5.010;usestrict;usewarnings;useDigest::CRCqw( crc32 );my$crc=Digest::CRC->new(type=>"crc32");$crc->add("The quick brown fox jumps over the lazy dog");say"The checksum is ".$crc->hexdigest();
Output:
The checksum is 414fa339

Phix

Included as demo\rosetta\crc32.exw, which also includes a thread-safe version

withjavascript_semanticssequencetableboolhave_table=falsefunctioncrc32(strings)ifnothave_tablethenhave_table=truetable=repeat(0,256)fori=0to255doatomrem=iforj=1to8doifand_bits(rem,1)thenrem=xor_bits(floor(rem/2),#EDB88320)elserem=floor(rem/2)endififrem<0thenrem+=#100000000endifendfortable[i+1]=remendforendifatomcrc=#FFFFFFFFfori=1tolength(s)docrc=xor_bits(floor(crc/#100),table[xor_bits(and_bits(crc,0xff),s[i])+1])ifcrc<0thencrc+=#100000000endifendforreturnand_bits(not_bits(crc),#FFFFFFFF)endfunctionstrings="The quick brown fox jumps over the lazy dog"printf(1,"The CRC of %s is %08x\n",{s,crc32(s)})
Output:
The CRC of The quick brown fox jumps over the lazy dog is 414FA339

PHP

PHP has a built-in functioncrc32.

printf("%x\n",crc32("The quick brown fox jumps over the lazy dog"));
414fa339

PicoLisp

Library and implementation.

(setq *Table   (mapcar      '((N)         (do 8            (setq N               (if (bit? 1 N)                  (x| (>> 1 N) `(hex "EDB88320"))                  (>> 1 N) ) ) ) )      (range 0 255) ) ) (de crc32 (Lst)   (let Crc `(hex "FFFFFFFF")      (for I (chop Lst)         (setq Crc            (x|               (get                  *Table                  (inc (x| (& Crc 255) (char I))) )               (>> 8 Crc) ) ) )      (x| `(hex "FFFFFFFF") Crc) ) ) (let Str "The quick brown fox jumps over the lazy dog"   (println (hex (crc32 Str)))   (println      (hex (native "libz.so" "crc32" 'N 0 Str (length Str))) ) ) (bye)

Pike

stringfoo="The quick brown fox jumps over the lazy dog";write("0x%x\n",Gz.crc32(foo));
Output:
0x414fa339

PL/I

*process source attributes xref or(!) nest; crct: Proc Options(main); /********************************************************************* * 19.08.2013 Walter Pachl  derived from REXX *********************************************************************/ Dcl (LEFT,LENGTH,RIGHT,SUBSTR,UNSPEC) Builtin; Dcl SYSPRINT Print; dcl tab(0:255) Bit(32); Call mk_tab; Call crc_32('The quick brown fox jumps over the lazy dog'); Call crc_32('Generate CRC32 Checksum For Byte Array Example'); crc_32: Proc(s); /********************************************************************* * compute checksum for s *********************************************************************/ Dcl s Char(*); Dcl d   Bit(32); Dcl d1  Bit( 8); Dcl d2  Bit(24); Dcl cc  Char(1); Dcl ccb Bit(8); Dcl tib Bit(8); Dcl ti  Bin Fixed(16) Unsigned; Dcl k   Bin Fixed(16) Unsigned; d=(32)'1'b; Do k=1 To length(s);    d1=right(d,8);    d2=left(d,24);    cc=substr(s,k,1);    ccb=unspec(cc);    tib=d1^ccb;    Unspec(ti)=tib;    d='00000000'b!!d2^tab(ti);    End;  d=d^(32)'1'b;  Put Edit(s,'CRC_32=',b2x(d))(Skip,a(50),a,a);  Put Edit('decimal ',b2d(d))(skip,x(49),a,f(10)); End; b2x: proc(b) Returns(char(8)); dcl b bit(32); dcl b4 bit(4); dcl i Bin Fixed(31); dcl r Char(8) Var init(''); Do i=1 To 29 By 4;   b4=substr(b,i,4);   Select(b4);     When('0000'b) r=r!!'0';     When('0001'b) r=r!!'1';     When('0010'b) r=r!!'2';     When('0011'b) r=r!!'3';     When('0100'b) r=r!!'4';     When('0101'b) r=r!!'5';     When('0110'b) r=r!!'6';     When('0111'b) r=r!!'7';     When('1000'b) r=r!!'8';     When('1001'b) r=r!!'9';     When('1010'b) r=r!!'A';     When('1011'b) r=r!!'B';     When('1100'b) r=r!!'C';     When('1101'b) r=r!!'D';     When('1110'b) r=r!!'E';     When('1111'b) r=r!!'F';     End;   End; Return(r); End; b2d: Proc(b) Returns(Dec Fixed(15)); Dcl b Bit(32); Dcl r Dec Fixed(15) Init(0); Dcl i Bin Fixed(16); Do i=1 To 32;   r=r*2   If substr(b,i,1) Then     r=r+1;   End; Return(r); End; mk_tab: Proc; dcl b32 bit(32); dcl lb  bit( 1); dcl ccc bit(32) Init('edb88320'bx); dcl (i,j) Bin Fixed(15); Do i=0 To 255;   b32=(24)'0'b!!unspec(i);   Do j=0 To 7;     lb=right(b32,1);     b32='0'b!!left(b32,31);     If lb='1'b Then       b32=b32^ccc;     End;   tab(i)=b32;   End; End; End;
Output:
The quick brown fox jumps over the lazy dog       CRC_32=414FA339                                                 decimal 1095738169Generate CRC32 Checksum For Byte Array Example    CRC_32=D1370232                                                 decimal 3510043186

PowerBASIC

#COMPILE EXE#DIM ALL#COMPILER PBCC 6' ***********FUNCTION CRC32(BYVAL p AS BYTE PTR, BYVAL NumBytes AS DWORD) AS DWORD  STATIC LUT() AS DWORD  LOCAL i, j, k, crc AS DWORD  IF ARRAYATTR(LUT(), 0) = 0 THEN    REDIM LUT(0 TO 255)    FOR i = 0 TO 255      k = i      FOR j = 0 TO 7        IF (k AND 1) THEN          SHIFT RIGHT k, 1          k XOR= &HEDB88320        ELSE          SHIFT RIGHT k, 1        END IF      NEXT j      LUT(i) = k    NEXT i  END IF  crc = &HFFFFFFFF  FOR i = 0 TO NumBytes - 1    k = (crc AND &HFF& XOR @p[i])    SHIFT RIGHT crc, 8    crc XOR= LUT(k)  NEXT i  FUNCTION = NOT crcEND FUNCTION' ***********FUNCTION PBMAIN () AS LONG  LOCAL s AS STRING  LOCAL crc AS DWORD  s = "The quick brown fox jumps over the lazy dog"  CON.PRINT "Text:  " & s  crc = CRC32(STRPTR(s), LEN(s))  CON.PRINT "CRC32: " & HEX$(crc)END FUNCTION
Output:
Text:  The quick brown fox jumps over the lazy dogCRC32: 414FA339

PureBasic

Works with:PB Version 5.40
a$="The quick brown fox jumps over the lazy dog"UseCRC32Fingerprint():b$=StringFingerprint(a$,#PB_Cipher_CRC32)OpenConsole()PrintN("CRC32 Cecksum [hex] = "+UCase(b$))PrintN("CRC32 Cecksum [dec] = "+Val("$"+b$))Input()End
Output:
CRC32 Cecksum [hex] = 414FA339CRC32 Cecksum [dec] = 1095738169

Python

Library

zlib.crc32 andbinascii.crc32 give identical results.

>>>s='The quick brown fox jumps over the lazy dog'>>>importzlib>>>hex(zlib.crc32(s))'0x414fa339'>>>importbinascii>>>hex(binascii.crc32(s))'0x414fa339'

If you have Python 2.x, these functions might return a negative integer; you would need to use& 0xffffffff to get the same answer as Python 3.x. With Python 3.x, convert first the string to bytes, for instance withs.encode('UTF-8'), as these functions do not accept strings.

Implementation

Procedural

defcreate_table():a=[]foriinrange(256):k=iforjinrange(8):ifk&1:k^=0x1db710640k>>=1a.append(k)returnadefcrc_update(buf,crc):crc^=0xffffffffforkinbuf:crc=(crc>>8)^crc_table[(crc&0xff)^k]returncrc^0xffffffffcrc_table=create_table()print(hex(crc_update(b"The quick brown fox jumps over the lazy dog",0)))

Composition of pure functions

'''CRC-32 checksums for ascii strings'''fromfunctoolsimport(reduce)fromitertoolsimport(islice)# crc32 :: String -> Intdefcrc32(s):'''CRC-32 checksum for an ASCII encoded string'''defgo(x):x2=x>>1return0xedb88320^x2ifx&1elsex2table=[index(iterate(go)(n))(8)forninrange(0,256)]returnreduce(lambdaa,c:(a>>8)^table[(a^ord(c))&0xff],s,(0xffffffff))^0xffffffff# ------------------------- TEST -------------------------# main :: IO ()defmain():'''Test'''print(format(crc32('The quick brown fox jumps over the lazy dog'),'02x'))# ----------------------- GENERIC ------------------------# index (!!) :: [a] -> Int -> adefindex(xs):'''Item at given (zero-based) index.'''returnlambdan:Noneif0>nelse(xs[n]if(hasattr(xs,"__getitem__"))elsenext(islice(xs,n,None)))# iterate :: (a -> a) -> a -> Gen [a]defiterate(f):'''An infinite list of repeated       applications of f to x.    '''defgo(x):v=xwhileTrue:yieldvv=f(v)returngoif__name__=='__main__':main()
Output:
414fa339

QB64

Translation of:C
PRINT HEX$(crc32("The quick brown fox jumps over the lazy dog"))FUNCTION crc32~& (buf AS STRING)    STATIC table(255) AS _UNSIGNED LONG    STATIC have_table AS _BYTE    DIM crc AS _UNSIGNED LONG, k AS _UNSIGNED LONG    DIM i AS LONG, j AS LONG    IF have_table = 0 THEN        FOR i = 0 TO 255            k = i            FOR j = 0 TO 7                IF (k AND 1) THEN                    k = _SHR(k, 1)                    k = k XOR &HEDB88320                ELSE                    k = _SHR(k, 1)                END IF                table(i) = k            NEXT        NEXT        have_table = -1    END IF    crc = NOT crc ' crc = &Hffffffff    FOR i = 1 TO LEN(buf)        crc = (_SHR(crc, 8)) XOR table((crc AND &HFF) XOR ASC(buf, i))    NEXT    crc32~& = NOT crcEND FUNCTION
Output:
414FA339

Quackery

Translation of:Forth
  [ table ]                      is crctable ( n --> n )  256 times    [ i^ 8 times      [ dup 1 >>         swap 1 & if          [ hex EDB88320 ^ ] ]     ' crctable put ]  [ hex FFFFFFFF swap    witheach       [ over ^ hex FF &         crctable        swap 8 >> ^ ]      hex FFFFFFFF ^ ]            is crc-32   ( [ --> n )  $ "The quick brown fox jumps over the lazy dog" crc-32  16 base put   echo   base release
Output:
414FA339

R

digest("The quick brown fox jumps over the lazy dog","crc32",serialize=F)
Output:
[1] "414fa339"

Racket

#langracket(define(bytes-crc32data)(bitwise-xor(for/fold([accum#xFFFFFFFF])([byte(in-bytesdata)])(for/fold([accum(bitwise-xoraccumbyte)])([num(in-range08)])(bitwise-xor(quotientaccum2)(*#xEDB88320(bitwise-andaccum1)))))#xFFFFFFFF))(define(crc32s)(bytes-crc32(string->bytes/utf-8s)))(format"~x"(crc32"The quick brown fox jumps over the lazy dog"))
Output:
"414fa339"

Raku

(formerly Perl 6)

Call to native function crc32 in zlib

useNativeCall;subcrc32(int32$crc,Buf$buf,int32$len -->int32)isnative('z') { * }my$buf ='The quick brown fox jumps over the lazy dog'.encode;saycrc32(0,$buf,$buf.bytes).fmt('%08x');

The libary name "z" resolves to/usr/lib/libz.so on a typical Linux system and/usr/lib/libz.dylib on Mac OS X, but may need to be changed for other platforms. Types may be platform-dependent as well. As written, the solution has been tested on Mac OS X 10.5.8 and Arch Linux 2016.08.01 x86_64.

Output:
414fa339

Pure Raku

A fairly generic implementation with no regard to execution speed:

subcrc(Blob$buf,# polynomial including leading term, default: ISO 3309/PNG/gzip    :@poly = (1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,0,0,1,1,1,0,1,1,0,1,1,0,1,1,1),    :$n =@poly.end,# degree of polynomial    :@init =1xx$n,# initial XOR bits    :@fini =1xx$n,# final XOR bits    :@bitorder =0..7,# default: eat bytes LSB-first    :@crcorder =0..$n-1,# default: MSB of checksum is coefficient of x⁰) {my@bit =flat ($buf.listX+& (1X+<@bitorder))».so».Int,0xx$n;@bit[0   ..$n-1] «+^=»@init;@bit[$_  ..$_+$n] «+^=»@polyif@bit[$_]for0..@bit.end-$n;@bit[*-$n..  *-1] «+^=»@fini;    :2[@bit[@bit.endX-@crcorder]];}saycrc('The quick brown fox jumps over the lazy dog'.encode('ascii')).base(16);
Output:
414FA339

REXX

/*REXX program computes the  CRC─32  (32 bit Cyclic Redundancy Check)  checksum  for a  *//*─────────────────────────────────given string  [as described in ISO 3309, ITU─T V.42].*/callshow'The quick brown fox jumps over the lazy dog'/*the 1st string.*/callshow'Generate CRC32 Checksum For Byte Array Example'/* "  2nd    "   */exit/*stick a fork in it,  we're all done. *//*──────────────────────────────────────────────────────────────────────────────────────*/CRC_32:procedure;parsearg!,$;c='edb88320'x/*2nd arg used for repeated invocations*/f='ffFFffFF'x/* [↓]  build an  8─bit  indexed table,*/doi=0for256;z=d2c(i)/*                  one byte at a time.*/r=right(z,4,'0'x)/*insure the  "R"   is thirty─two bits.*//* [↓]  handle each rightmost byte bit.*/doj=0for8;rb=x2b(c2x(r))/*handle each bit of rightmost 8 bits. */r=x2c(b2x(0||left(rb,31)))/*shift it right (an unsigned)  1  bit.*/ifright(rb,1)thenr=bitxor(r,c)/*this is a bin bit for XOR grunt─work.*/end/*j*/!.z=r/*assign to an eight─bit index table.  */end/*i*/$=bitxor(word($'0000000'x,1),f)/*utilize the user's CRC or a default. */dok=1forlength(!)/*start number crunching the input data*/?=bitxor(right($,1),substr(!,k,1))$=bitxor('0'x||left($,3),!.?)end/*k*/return$/*return with cyclic redundancy check. *//*──────────────────────────────────────────────────────────────────────────────────────*/show:procedure;parseargXstring;numericdigits12;say;saychecksum=bitxor(CRC_32(Xstring),'ffFFffFF'x)/*invoke CRC_32 to create a CRC. */saycenter(' input string [length of'length(Xstring)"bytes] ",79,'═')sayXstring;say/*show the string on its own line*/say"hex CRC─32 checksum ="c2x(checksum)left('',15),"dec CRC─32 checksum ="c2d(checksum)/*show the CRC─32 in hex and dec.*/return
output  when using the internal default input:
══════════════════════ input string [length of 43 bytes] ══════════════════════The quick brown fox jumps over the lazy doghex CRC-32 checksum = 414FA339                 dec CRC-32 checksum = 1095738169══════════════════════ input string [length of 46 bytes] ══════════════════════Generate CRC32 Checksum For Byte Array Examplehex CRC-32 checksum = D1370232                 dec CRC-32 checksum = 3510043186

RPL

Translation of:FreeBASIC
≪ → string  ≪32 STWS@ set binary word size to 32IFERRCRCtable’ RCLTHEN       { }0 255FOR j         j R→B0 7START           SRIF LAST#1 AND B→RTHEN#EDB88320h XORENDNEXT +NEXTCRCtable’ STOEND     DROP#0 NOT1 string SIZEFOR j       SRB SWAP#FFh AND string j DUP SUB NUM R→B XOR       B→R1 + ‘CRCtable’ SWAP GET XORNEXT      NOT≫ ≫ ‘CRC32’ STO
"The quick brown fox jumps over the lazy dog"CRC32
Output:
1: # 414FA339h

Ruby

Use 'zlib' from standard library.

require'zlib'printf"0x%08x\n",Zlib.crc32('The quick brown fox jumps over the lazy dog')# => 0x414fa339

Reimplement CRC-32 in Ruby, with comments to show the polynomials.

moduleCRC# Divisor is a polynomial of degree 32 with coefficients modulo 2.# We store Divisor in a 33-bit Integer; the polynomial is#   Divisor[32] + Divisor[31] * x + ... + Divisor[0] * x**32Divisor=[0,1,2,4,5,7,8,10,11,12,16,22,23,26,32]\.inject(0){|sum,exponent|sum+(1<<(32-exponent))}# This table gives the crc (without conditioning) of every possible# _octet_ from 0 to 255. Each _octet_ is a polynomial of degree 7,#   octet[7] + octet[6] * x + ... + octet[0] * x**7# Then remainder = Table[octet] is the remainder from# _octet_ times x**32 divided by Divisor,#   remainder[31] + remainder[30] + ... + remainder[0] * x**31Table=Array.new(256)do|octet|# Find remainder from polynomial long division.#    octet[ 7] * x**32 + ... +   octet[0] * x**39#  Divisor[32] * x**0  + ... + Divisor[0] * x**32remainder=octet(0..7).eachdo|i|# Find next term of quotient. To simplify the code,# we assume that Divisor[0] is 1, and we only check# remainder[i]. We save remainder, forget quotient.ifremainder[i].zero?# Next term of quotient is 0 * x**(7 - i).# No change to remainder.else# Next term of quotient is 1 * x**(7 - i). Multiply# this term by Divisor, then subtract from remainder.#  * Multiplication uses left shift :<< to align#    the x**(39 - i) terms.#  * Subtraction uses bitwise exclusive-or :^.remainder^=(Divisor<<i)endendremainder>>8# Remove x**32 to x**39 terms.endmodule_functiondefcrc32(string,crc=0)# Pre-conditioning: Flip all 32 bits. Without this step, a string# preprended with extra "\0" would have same crc32 value.crc^=0xffff_ffff# Iterate octets to perform polynomial long division.string.each_bytedo|octet|# Update _crc_ by continuing its polynomial long division.# Our current remainder is old _crc_ times x**8, plus# new _octet_ times x**32, which is#   crc[32] * x**8 + crc[31] * x**9 + ... + crc[8] * x**31 \#     + (crc[7] + octet[7]) * x**32 + ... \#     + (crc[0] + octet[0]) * x**39## Our new _crc_ is the remainder from this polynomial divided by# Divisor. We split the terms into part 1 for x**8 to x**31, and# part 2 for x**32 to x**39, and divide each part separately.# Then remainder 1 is trivial, and remainder 2 is in our Table.remainder_1=crc>>8remainder_2=Table[(crc&0xff)^octet]# Our new _crc_ is sum of both remainders. (This sum never# overflows to x**32, so is not too big for Divisor.)crc=remainder_1^remainder_2end# Post-conditioning: Flip all 32 bits. If we later update _crc_,# this step cancels the next pre-conditioning.crc^0xffff_ffffendendprintf"0x%08x\n",CRC.crc32("The quick brown fox jumps over the lazy dog")# => 0x414fa339

Rust

This does not perform any caching of the lookup table for simplicity.

fncrc32_compute_table()->[u32;256]{letmutcrc32_table=[0;256];fornin0..256{crc32_table[nasusize]=(0..8).fold(nasu32,|acc,_|{matchacc&1{1=>0xedb88320^(acc>>1),_=>acc>>1,}});}crc32_table}fncrc32(buf:&str)->u32{letcrc_table=crc32_compute_table();!buf.bytes().fold(!0,|acc,octet|{(acc>>8)^crc_table[((acc&0xff)^octetasu32)asusize]})}fnmain(){println!("{:x}",crc32("The quick brown fox jumps over the lazy dog"));}
Output:
414fa339

Scala

Translation of:Java
importjava.util.zip.CRC32valcrc=newCRC32crc.update("The quick brown fox jumps over the lazy dog".getBytes)println(crc.getValue.toHexString)//> 414fa339

Seed7

$ include "seed7_05.s7i";  include "crc32.s7i";const proc: main is func  begin    writeln(ord(crc32("The quick brown fox jumps over the lazy dog")) radix 16 lpad0 8);  end func;
Output:
414fa339

Shell

Bash

#!/usr/bin/env bashdeclare-i-aCRC32_LOOKUP_TABLE__generate_crc_lookup_table(){local-i-rLSB_CRC32_POLY=0xEDB88320# The CRC32 polynomal LSB orderlocal-iindexbytelsbforindexin{0..255};do((byte=255-index))for_in{0..7};do# 8-bit lsb shift((lsb=byte&0x01,byte=((byte>>1)&0x7FFFFFFF)^(lsb==0?LSB_CRC32_POLY:0)))done((CRC32_LOOKUP_TABLE[index]=byte))done}__generate_crc_lookup_tabletypeset-rCRC32_LOOKUP_TABLEcrc32_string(){[[${#}-eq1]]||returnlocal-iibytecrc=0xFFFFFFFFindexfor((i=0;i<${#1};i++));dobyte=$(printf'%d'"'${1:i:1}")# Get byte value of character at i((index=(crc^byte)&0xFF,crc=(CRC32_LOOKUP_TABLE[index]^(crc>>8))&0xFFFFFFFF))doneecho$((crc^0xFFFFFFFF))}printf'The CRC32 of: %s\nis: 0x%08x\n'"${1}""$(crc32_string"${1}")"# crc32_string "The quick brown fox jumps over the lazy dog"# yields 414fa339

POSIX

The POSIX Shell has no array type and no string indexation.It costs less to recompute polynomal shift for each character than indexingwith external tools likeawk ortr.

#!/usr/bin/env sh# POSIX Shell CRC32 of string# @Name: crc32.sh# @Version: 1.0.1# @Author: Léa Gris <lea.gris@noiraude.net># @Date: Wed, 27 Mar 2019# @License: WTFPL http://www.wtfpl.net/# POSIX Shell has no array or string index# Implementing a pre-computed CRC32 byte indexed look-up table# would cost more CPU cycles calling external tools like# awk or tr to index records from a string.# Computes the CRC32 of the input data stream# <&1: The input data stream# >&1: The CRC32 integer of the input data streamcrc32_stream(){crc=0xFFFFFFFF# The Initial CRC32 valuep=0xedb88320# The CRC32 polynomialr=0# The polynomial reminderc=''# The current characterbyte=0# The byte value of the current character# Iterates each character of the input streamwhilec="$(ddbs=1count=12>/dev/null)"&&[-n"$c"];dobyte=$(printf'%d'"'$c")# Converts the character into its byte valuer=$(((crc&0xff)^byte))# XOR LSB of CRC with current byte# 8-bit lsb shift with XOR polynomial reminder when oddfor_in________;dot=$((r>>1))r=$(((r&1)?t^p:t))donecrc=$(((crc>>8)^r))# XOR MSB of CRC with Reminderdone# Output CRC32 integer XOR mask 32 bitsecho$((crc^0xFFFFFFFF))}# Computes the CRC32 of the argument string# 1: The argument string# >&1: The CRC32 integer of the argument stringcrc32_string(){[$#-eq1]||return# argument required# Streams with printf to prevent suffixing the string# with a newline, since echo -n is not available in POSIX Shellprintf'%s'"$1"|crc32_stream}printf'The CRC32 of: %s\nis: %08x\n'"$1""$(crc32_string"$1")"# crc32_string "The quick brown fox jumps over the lazy dog"# yields 414fa339
Output:
bash ./crc32.sh "The quick brown fox jumps over the lazy dog"The CRC32 of: The quick brown fox jumps over the lazy dogis: 0x414fa339

Sidef

funccreate_crc32_table{256.of{|k|8.times{if(k&1){k>>=1k^=0xedb88320}else{k>>=1}}k}}funccrc32(str,crc=0){staticcrc_table=create_crc32_table()crc&=0xffffffffcrc^=0xffffffffstr.codes.each{|c|crc=((crc>>8)^crc_table[(crc&0xff)^c])}return((crc&0xffffffff)^0xffffffff)}saycrc32("The quick brown fox jumps over the lazy dog").as_hexsaycrc32("over the lazy dog",crc32("The quick brown fox jumps ")).as_hex
Output:
414fa339414fa339

Smalltalk

Works with:Smalltalk/X

the CRC32Stream utility class can do it for me:

CRC32StreamhashValueOf:'The quick brown fox jumps over the lazy dog'
Output:
1095738169 "which is 16r414FA339"

Swift

Using the zlib crc32 function available to Swift from libz.dylib.

importFoundationletstrData="The quick brown fox jumps over the lazy dog".dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion:false)letcrc=crc32(uLong(0),UnsafePointer<Bytef>(strData!.bytes),uInt(strData!.length))println(NSString(format:"%2X",crc))
Output:
414FA339

Tcl

packagerequireTcl8.6setdata"The quick brown fox jumps over the lazy dog"puts[format"%x"[zlibcrc32$data]]
Output:
414fa339

Alternatively, with older versions of Tcl:

Library:Tcllib(Package: crc32)
packagerequirecrc32puts[format"%x"[crc::crc32$data]]

With the same input data, it produces identical output.

TXR

Standard Library

(crc32 "The quick brown fox jumps over the lazy dog")
Output:
1095738169

FFI access to Zlib

(with-dyn-lib "libz.so.1"  (deffi zlib-crc32 "crc32" ulong (ulong str uint)))
Output:
$ txr -i crc32-zlib.tl 1> (let ((s "The quick brown fox jumps over the lazy dog"))      (zlib-crc32 0 s (coded-length s)))1095738169

Note:coded-length gives UTF-8 length;len yields a code point count. Since this is an ASCII string, the two agree.

Lisp Code

(defvarl crc-tab  #(#x00000000 #x77073096 #xee0e612c #x990951ba #x076dc419 #x706af48f    #xe963a535 #x9e6495a3 #x0edb8832 #x79dcb8a4 #xe0d5e91e #x97d2d988    #x09b64c2b #x7eb17cbd #xe7b82d07 #x90bf1d91 #x1db71064 #x6ab020f2    #xf3b97148 #x84be41de #x1adad47d #x6ddde4eb #xf4d4b551 #x83d385c7    #x136c9856 #x646ba8c0 #xfd62f97a #x8a65c9ec #x14015c4f #x63066cd9    #xfa0f3d63 #x8d080df5 #x3b6e20c8 #x4c69105e #xd56041e4 #xa2677172    #x3c03e4d1 #x4b04d447 #xd20d85fd #xa50ab56b #x35b5a8fa #x42b2986c    #xdbbbc9d6 #xacbcf940 #x32d86ce3 #x45df5c75 #xdcd60dcf #xabd13d59    #x26d930ac #x51de003a #xc8d75180 #xbfd06116 #x21b4f4b5 #x56b3c423    #xcfba9599 #xb8bda50f #x2802b89e #x5f058808 #xc60cd9b2 #xb10be924    #x2f6f7c87 #x58684c11 #xc1611dab #xb6662d3d #x76dc4190 #x01db7106    #x98d220bc #xefd5102a #x71b18589 #x06b6b51f #x9fbfe4a5 #xe8b8d433    #x7807c9a2 #x0f00f934 #x9609a88e #xe10e9818 #x7f6a0dbb #x086d3d2d    #x91646c97 #xe6635c01 #x6b6b51f4 #x1c6c6162 #x856530d8 #xf262004e    #x6c0695ed #x1b01a57b #x8208f4c1 #xf50fc457 #x65b0d9c6 #x12b7e950    #x8bbeb8ea #xfcb9887c #x62dd1ddf #x15da2d49 #x8cd37cf3 #xfbd44c65    #x4db26158 #x3ab551ce #xa3bc0074 #xd4bb30e2 #x4adfa541 #x3dd895d7    #xa4d1c46d #xd3d6f4fb #x4369e96a #x346ed9fc #xad678846 #xda60b8d0    #x44042d73 #x33031de5 #xaa0a4c5f #xdd0d7cc9 #x5005713c #x270241aa    #xbe0b1010 #xc90c2086 #x5768b525 #x206f85b3 #xb966d409 #xce61e49f    #x5edef90e #x29d9c998 #xb0d09822 #xc7d7a8b4 #x59b33d17 #x2eb40d81    #xb7bd5c3b #xc0ba6cad #xedb88320 #x9abfb3b6 #x03b6e20c #x74b1d29a    #xead54739 #x9dd277af #x04db2615 #x73dc1683 #xe3630b12 #x94643b84    #x0d6d6a3e #x7a6a5aa8 #xe40ecf0b #x9309ff9d #x0a00ae27 #x7d079eb1    #xf00f9344 #x8708a3d2 #x1e01f268 #x6906c2fe #xf762575d #x806567cb    #x196c3671 #x6e6b06e7 #xfed41b76 #x89d32be0 #x10da7a5a #x67dd4acc    #xf9b9df6f #x8ebeeff9 #x17b7be43 #x60b08ed5 #xd6d6a3e8 #xa1d1937e    #x38d8c2c4 #x4fdff252 #xd1bb67f1 #xa6bc5767 #x3fb506dd #x48b2364b    #xd80d2bda #xaf0a1b4c #x36034af6 #x41047a60 #xdf60efc3 #xa867df55    #x316e8eef #x4669be79 #xcb61b38c #xbc66831a #x256fd2a0 #x5268e236    #xcc0c7795 #xbb0b4703 #x220216b9 #x5505262f #xc5ba3bbe #xb2bd0b28    #x2bb45a92 #x5cb36a04 #xc2d7ffa7 #xb5d0cf31 #x2cd99e8b #x5bdeae1d    #x9b64c2b0 #xec63f226 #x756aa39c #x026d930a #x9c0906a9 #xeb0e363f    #x72076785 #x05005713 #x95bf4a82 #xe2b87a14 #x7bb12bae #x0cb61b38    #x92d28e9b #xe5d5be0d #x7cdcefb7 #x0bdbdf21 #x86d3d2d4 #xf1d4e242    #x68ddb3f8 #x1fda836e #x81be16cd #xf6b9265b #x6fb077e1 #x18b74777    #x88085ae6 #xff0f6a70 #x66063bca #x11010b5c #x8f659eff #xf862ae69    #x616bffd3 #x166ccf45 #xa00ae278 #xd70dd2ee #x4e048354 #x3903b3c2    #xa7672661 #xd06016f7 #x4969474d #x3e6e77db #xaed16a4a #xd9d65adc    #x40df0b66 #x37d83bf0 #xa9bcae53 #xdebb9ec5 #x47b2cf7f #x30b5ffe9    #xbdbdf21c #xcabac28a #x53b39330 #x24b4a3a6 #xbad03605 #xcdd70693    #x54de5729 #x23d967bf #xb3667a2e #xc4614ab8 #x5d681b02 #x2a6f2b94    #xb40bbe37 #xc30c8ea1 #x5a05df1b #x2d02ef8d))(defun crc32 (buf)  (let ((crc #xffffffff)        (l (len buf)))    (each ((i 0..l))      (set crc (logxor [crc-tab (logand (logxor crc [buf i]) #xff)]                       (ash crc -8))))    (logxor crc #xffffffff)))
Output:
$ ./txr -i crc.tl warning: (crc.tl:46) defun: redefining crc32, which is a built-in defun1> (crc32 (buf-str "The quick brown fox jumps over the lazy dog"))1095738169

Vala

Library

usingZLib.Utility;voidmain(){varstr=(uint8[])"The quick brown fox jumps over the lazy dog".to_utf8();stdout.printf("%lx\n",crc32(0,str));}
Output:
414fa339

Implementation

publicclassCrc32{privateconstuint32s_generator=0xedb88320u;publicCrc32(){m_table=newuint32[256];uint32rem;for(uint32i=0;i<256;i++){rem=i;for(uint32j=0;j<8;j++){if((rem&1)!=0){rem>>=1;rem^=s_generator;}elserem>>=1;}m_table[i]=rem;}}publicuint32get(stringstr){uint32crc=0;crc=~crc;for(inti=0;i<str.length;i++){crc=(crc>>8)^m_table[(crc&0xff)^str[i]];}return~crc;}privateuint32[]m_table;}voidmain(){varcrc32=newCrc32();stdout.printf("%x\n",crc32.get("The quick brown fox jumps over the lazy dog"));}
Output:
414fa339

VAX Assembly

                           EDB88320  0000     1 poly:   .long   ^xedb88320                      ;crc32                           00000044  0004     2 table:  .blkl   16                                     0044     3          4C 58 21 0000004C'010E0000' 0044     4 fmt:    .ascid  "!XL"                           ;result format36 35 34 33 32 31 00000057'010E0000' 004F     5 result: .ascid  "12345678"                      ; and buffer                              38 37  005D                                      0000  005F     6 .entry  crc,0                         A0 AF   7F  0061     7         pushaq  table                           ;fill table                         99 AF   DF  0064     8         pushal  poly                            ; for              00000000'GF   02   FB  0067     9         calls   #2, g^lib$crc_table             ;  crc opcode      2B'  FFFFFFFF 8F   93 AF   0B  006E    10         crc     table, #-1, s^#len, b^msg       ;table,init,len,string                         98'AF       0077                              50   50   D2  0079    11         mcoml   r0, r0                          ;invert result                                     007C    12         $fao_sctrstr = fmt, outbuf = result, p1 = r0 ; format                         BF AF   7F  008D    13 pushaqresult;and show              00000000'GF   01   FB  0090    14         calls   #1, g^lib$put_output            ;  result 414fa339                                 04  0097    15         ret                                     0098    16 72 62 20 6B 63 69 75 71 20 65 68 54  0098    17 msg:    .ascii  "The quick brown fox jumps over the lazy dog"70 6D 75 6A 20 78 6F 66 20 6E 77 6F  00A4       6C 20 65 68 74 20 72 65 76 6F 20 73  00B0                      67 6F 64 20 79 7A 61  00BC                                  0000002B  00C3    18 len = .-msg                                     00C3    19 .endcrc

VBScript

VBScript does'nt have bit rotation instructions and then bit to bit logic converts the default Double values to SIGNED 32 bit integers and back. A table driven implementation is required to speed things up. The code generates the table on the fly.

dimcrctbl(255)constcrcc=&hEDB88320subgencrctablefori=0to255k=iforj=1to8ifkand1thenk=(kand&h7fffffff)\2or(&h40000000and((kand&h80000000)<>0))k=kxorcrccelsek=(kand&h7fffffff)\2or(&h40000000and((kand&h80000000)<>0))endifnext' jcrctbl(i)=knextendsubfunctioncrc32(buf)dimr,r1,ir=&hfffffffffori=1tolen(buf)r1=(rand&h7fffffff)\&h100or(&h800000and(rand&h80000000)<>0)r=r1xorcrctbl((asc(mid(buf,i,1))xorr)and255)nextcrc32=rxor&hffffffffendfunction'414FA339gencrctablewscript.stdout.writelinehex(crc32("The quick brown fox jumps over the lazy dog"))

Output

414FA339

Visual Basic

Works with:Visual Basic version 5
Works with:Visual Basic version 6
Works with:VBA version Access 97
Works with:VBA version 6.5
Works with:VBA version 7.1
Library:Win32

Not an ideal task for Visual Basic because the language lacks bit shifting operators (which can of course be emulated, but that's slow). Then again, since the only platform supported by VB is Microsoft Windows (32 Bit Subsystem), we can let the Windows API do the work for us. RtlComputeCrc32() was available since Windows XP and is still present in Windows 10.

OptionExplicitDeclareFunctionRtlComputeCrc32Lib"ntdll.dll"_(ByValdwInitialAsLong,pDataAsAny,ByValiLenAsLong)AsLong'--------------------------------------------------------------------SubMain()DimsAsStringDimb()AsByteDimlAsLongs="The quick brown fox jumps over the lazy dog"b()=StrConv(s,vbFromUnicode)'convert Unicode to ASCIIl=RtlComputeCrc32(0&,b(0),Len(s))Debug.Assertl=&H414FA339EndSub

Visual Basic .NET

Allows the resumption of calculations, useful for processing a large file with a series of buffer reads.

PublicClassCrc32' Table for pre-calculated values.Sharedtable(255)AsUInteger' Initialize tableSharedSubNew()ForiAsUInteger=0Totable.Length-1DimteAsUInteger=i' table entryForjAsInteger=0To7If(teAnd1)=1Thente=(te>>1)Xor&HEDB88320UIElsete>>=1Nexttable(i)=teNextEndSub' Return checksum calculation for Byte Array,'  optionally resuming (used when breaking a large file into read-buffer-sized blocks).' Call with Init = False to continue calculation.PublicSharedFunctioncs(BAAsByte(),OptionalInitAsBoolean=True)AsUIntegerStaticcrcAsUIntegerIfInitThencrc=UInteger.MaxValueForEachbInBAcrc=(crc>>8)Xortable((crcAnd&HFF)Xorb)NextReturnNotcrcEndFunctionEndClass

Test:

' Returns a Byte Array from a string of ASCII characters.FunctionStr2BA(StrAsString)AsByte()ReturnSystem.Text.Encoding.ASCII.GetBytes(Str)EndFunction' Returns a Hex string from an UInteger, formatted to a number of digits,'  adding leading zeros If necessary.FunctionHexF(ValueAsUInteger,DigitsAsInteger)AsStringHexF=Hex(Value)IfLen(HexF)<DigitsThenHexF=StrDup(Digits-Len(HexF),"0")&HexFEndFunction' Tests Crc32 classSubTest()DimStrAsString="The quick brown fox jumps over the lazy dog"Debug.Print("Input = """&Str&"""")' Convert string to Byte Array, compute crc32, and display formatted resultDebug.Print("Crc32 = "&HexF(Crc32.cs(Str2BA(Str)),8))' This next code demonstrates continuing a crc32 calculation when breaking the input' into pieces, such as processing a large file by a series of buffer reads.Crc32.cs(Str2BA(Mid(Str,1,20)))Debug.Print("Crc32 = "&HexF(Crc32.cs(Str2BA(Mid(Str,21)),False),8))EndSub

Output:

Input = "The quick brown fox jumps over the lazy dog"Crc32 = 414FA339Crc32 = 414FA339

V (Vlang)

import hash.crc32fn main() {    text := "The quick brown fox jumps over the lazy dog"    result := crc32.sum(text.bytes())    println(result.hex())}
Output:
414fa339

Wren

Translation of:Go
Library:Wren-fmt
import"./fmt"forConvclassCRC32{staticinit(){__table=List.filled(256,0)for(iin0..255){varword=ifor(jin0..7){if(word&1==1){word=(word>>1)^0xedb88320}else{word=word>>1}}__table[i]=word}}staticcompute(s){varcrc=~0varle=s.bytes.countfor(iin0...le){varcrb=crc&0xffcrc=__table[crb^s[i].bytes[0]]^(crc>>8)}return~crc}}CRC32.init()varcrc=CRC32.compute("The quick brown fox jumps over the lazy dog")System.print(Conv.hex(crc))
Output:
414fa339

XPL0

code HexOut=27;         \intrinsic routinestring 0;               \use zero-terminated stringsfunc CRC32(Str, Len);   \Return CRC-32 for given stringchar Str;  int Len;     \byte array, number of bytesint  I, J, R, C;[R:= -1;                \initialize with all 1'sfor J:= 0 to Len-1 do    [C:= Str(J);    for I:= 0 to 8-1 do \for each bit in byte...        [if (R xor C) and 1 then R:= R>>1 xor $EDB88320        else R:= R>>1;        C:= C>>1;        ];    ];return not R;];HexOut(0, CRC32("The quick brown fox jumps over the lazy dog", 43))
Output:
414FA339

zkl

Using zlib:

var [const] ZLib=Import("zeelib");ZLib.calcCRC32(Data(Void,"The quick brown fox jumps over the lazy dog"));//-->0x414fa339

Zig

conststd=@import("std");constCrc32Ieee=std.hash.Crc32;pubfnmain()!void{constres:u32=Crc32Ieee.hash("The quick brown fox jumps over the lazy dog");std.debug.print("{x}\n",.{res});}
Output:
414fa339
Retrieved from "https://rosettacode.org/wiki/CRC-32?oldid=374439"
Categories:
Hidden category:
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

[8]ページ先頭

©2009-2025 Movatter.jp