CRC-32: Difference between revisions

Content added Content deleted
Line 2,110: Line 2,110:
It costs less to recompute polynomal shift for each character than indexing
It costs less to recompute polynomal shift for each character than indexing
with external tools like <code>awk</code> or <code>tr</code>.
with external tools like <code>awk</code> or <code>tr</code>.
<lang Bash>#!/bin/sh
<lang bash>#!/usr/bin/env sh
# POSIX Shell CRC32 of string
# POSIX Shell CRC32 of string
# @Name: crc32.sh
# @Name: crc32.sh
# @Version: 1.0.0
# @Version: 1.0.1
# @Author: Léa Gris <lea.gris@noiraude.net>
# @Author: Léa Gris <lea.gris@noiraude.net>
# @Date: Wed, 27 Mar 2019
# @Date: Wed, 27 Mar 2019
Line 2,128: Line 2,128:
crc32_stream() {
crc32_stream() {
crc=0xFFFFFFFF # The Initial CRC32 value
crc=0xFFFFFFFF # The Initial CRC32 value
p=0xedb88320 # The CRC32 polynomal
p=0xedb88320 # The CRC32 polynomial
r=0 # The polynomal reminder
r=0 # The polynomial reminder
c='' # The current character
c='' # The current character
byte=0 # Tge byte value of the current character
byte=0 # The byte value of the current character
# Iterates each character of the input stream
# Iterates each character of the input stream
while c="$(dd bs=1 count=1 2>/dev/null)" && [ -n "$c" ]; do
while c="$(dd bs=1 count=1 2>/dev/null)" && [ -n "$c" ]; do
byte=$(printf '%d' "'${c}") # Converts the character into its byte value
byte=$(printf '%d' "'$c") # Converts the character into its byte value
r=$(((crc & 0xff) ^ byte)) # XOR LSB of CRC with current byte
r=$(((crc & 0xff) ^ byte)) # XOR LSB of CRC with current byte
# 8-bit lsb shift with XOR polynomial reminder when odd
b=0 # bit index
# 8-bit lsb shift with XOR polynomal reminder when odd
for _ in _ _ _ _ _ _ _ _; do
while [ $((b <= 7)) -ne 0 ] && b=$((b + 1)); do
t=$((r >> 1))
r=$(((r & 0x1) ? (r >> 1) ^ p : r >> 1))
r=$(((r & 1) ? t ^ p : t))
done
done
crc=$(((crc >> 8) ^ r)) # XOR MSB of CRC with Reminder
crc=$(((crc >> 8) ^ r)) # XOR MSB of CRC with Reminder
Line 2,148: Line 2,148:
}
}


# Computes the CRC32 of argument string
# Computes the CRC32 of the argument string
# 1: The argument string
# 1: The argument string
# >&1: The CRC32 integer of the argument string
# >&1: The CRC32 integer of the argument string
crc32_string() {
crc32_string() {
[ $# -eq 1 ] || return # argument required
[ $# -eq 1 ] || return # argument required
# Streams with printf to prevent postfixing the string
# Streams with printf to prevent suffixing the string
# with a newline, since echo -n is not available in POSIX Shell
# with a newline, since echo -n is not available in POSIX Shell
printf '%s' "$1" | crc32_stream
printf '%s' "$1" | crc32_stream