CRC-32: Difference between revisions
Content added Content deleted
m (→POSIX) |
|||
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 |
<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. |
# @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 |
p=0xedb88320 # The CRC32 polynomial |
||
r=0 # The |
r=0 # The polynomial reminder |
||
c='' # The current character |
c='' # The current character |
||
byte=0 # |
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' "'$ |
byte=$(printf '%d' "'$c") # Converts the character into its byte value |
||
r=$(((crc & 0xff) ^ 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 |
|||
for _ in _ _ _ _ _ _ _ _; do |
|||
t=$((r >> 1)) |
|||
r=$(((r & |
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 |
# 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 |