CRC32 Calculation in 256 Bytes

Display mode

Back to Quick Hacks

The following program is in nasm format, and assembles to a DOS .com executable of 240 bytes.

The program is based on Horst Schäffer's 784-byte CRC32 calculator, which is part of the PBATS32 collection.

crc32.asm: A CRC32 calculator

[bits 16]
	org 0x0100
start:
	mov di,CMDBUF
	mov cx,0x7800
	xor ax,ax
	rep stosw

	mov di,LUTBUF
	xor cx,cx
.lutolp:
	xor dx,dx
	mov ax,cx
	mov ch,8
.lutlp:
	shr dx,1
	rcr ax,1
	jnc .xorskip
	xor dx,0xEDB8
	xor ax,0x8320
.xorskip:
	dec ch
	jnz .lutlp
	stosw
	mov ax,dx
	stosw
	inc cx
	and ch,ch
	jz .lutolp

	mov si,0x81
	mov di,CMDBUF
	mov dx,di
.getarg:
	lodsb
	cmp al,' '
	je .getarg
	jb .aend
	cmp al,','
	je .aend
	cmp al,'/'
	je .aend
	stosb
	jmp short .getarg

.aend:
	cmp dx,di
	je printhelp

	push di
	mov ax,0x3D40
	int 0x21
	jc printhelp
	mov bp,ax
	mov di,LUTBUF
	xor ax,ax
	dec ax
	cwd
.crcolp:
	push ax
	push dx
	mov si,READBUF
	mov dx,si
	mov cx,READBLEN
	mov bx,bp
	mov ah,0x3F
	int 0x21
	mov cx,ax
	pop dx
	pop ax
	jc .crcend
	jcxz .crcdone
.crclp:
	mov bx,ax
	lodsb
	xor bx,ax
	shl bx,2
	mov al,ah
	mov ah,dl
	mov dl,dh
	xor dh,dh
	xor ax,[bx+di]
	xor dx,[bx+di+2]
	loop .crclp
	cmp si,READBUF+READBLEN
	jnc .crcolp
.crcdone:
	not ax
	not dx
.crcend:
	push ax
	mov bx,bp
	mov ah,0x3e
	int 0x21
	pop bx

	pop di
	mov al,' '
	stosb
	mov cx,4
.prn:
	mov al,dh
	mov dh,dl
	mov dl,bh
	mov bh,bl
	call byteascii
	loop .prn

	mov ax,0x0a0d
	stosw
	mov al,'$'
	stosb

	mov dx,CMDBUF
	jmp short printmsg

printhelp:
	mov dx,msghelp
printmsg:
	mov ah,9
	int 0x21
	ret

byteascii:
	xor ah,ah
	div byte [divider]
	call .inner
	xchg ah,al
.inner:
	cmp al,10
	sbb al,0x69
	das
	stosb
	ret

divider:
	db 16

msghelp:
	db "Usage: CRC32 <file>",13,10,'$'

CMDBUF		equ 0x03C3
LUTBUF		equ 0x0468
READBUF		equ 0x0968
READBLEN	equ 0xC000