Created
June 3, 2024 16:14
-
-
Save loplex/83e6b7dbb1cfbb9e4f40da9a61dce93d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Computes the CRC16 - XMODEM (also known as ZMODEM or CRC-16/ACORN) | |
# rewritten to bash from C code found at: https://beebwiki.mdfs.net/CRC-16 | |
declare -i poly=0x1021 | |
declare -i init=0x0000 | |
function crc16() { | |
local input="$1" | |
local -i crc=${init} | |
local -i pos; for (( pos=0; pos<${#input}; pos++ )); do | |
local ord; LC_CTYPE=C printf -v ord '%d' "'${input:pos:1}" | |
crc=$(( crc ^ ( ord << 8 ) )) | |
# shellcheck disable=SC2034 | |
for i in {0..7}; do | |
crc=$(( crc << 1 )) | |
(( crc & 0x10000 )) && crc=$(( ( crc ^ poly ) & 0xFFFF )) | |
done | |
done | |
echo ${crc} | |
} | |
function crc16hex() { | |
local -i crc; crc=$(crc16 "$1") | |
printf '%04X\n' "${crc}" | |
} | |
function crc16mod16384() { | |
local -i crc; crc=$(crc16 "$1") | |
printf '%d\n' "$(( crc % 16384 ))" | |
} | |
crc16hex "$1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment