Skip to content

Instantly share code, notes, and snippets.

@mjf
Last active May 19, 2022 10:55
Show Gist options
  • Save mjf/8feb63ebe52ec691fe0b055db3b1a790 to your computer and use it in GitHub Desktop.
Save mjf/8feb63ebe52ec691fe0b055db3b1a790 to your computer and use it in GitHub Desktop.
Encode and Decode Crockford's BASE32 in pure shell
#! /bin/sh
# Encode and decode Crockford's BASE32
# Copyright (C) 2022 Matous Jan Fialka, <https://mjf.cz/>
# Released under the terms of the "MIT" license
# DO NOT USE FOR ANY REASON! This was just for some quick testing.
use() {
printf -- '%s -d <enc> | <dec>\n' "${0##*/}"
exit $1
}
loc() {
for val in ${sym[@]}; do
if [ $val = $1 ]; then
printf -- '%d' $ind
break
fi
ind=$((ind + 1))
done
}
[ $# -eq 0 ] && use
sym=({0..9} {A..H} J K M N {P..T} {V..Z}) bas=${#sym[@]}
if [ "$1" = '-d' ]; then
[ $# -ne 2 ] && use 1 >&2
str="$2" num=0 len=${#str}
while [ $len -gt 0 ]; do
chr="${str:$((${#str} - $len)):1}"
len=$(($len - 1))
num=$(($num*$bas + $(loc "$chr")))
done
printf -- '%d\n' $num
else
[ $# -ne 1 ] && use 1 >&2
num=$1 str=''
while [ $num -gt 0 ]; do
rem=$(($num%$bas))
num=$(($num/$bas))
str="${sym[$rem]}$str"
done
printf -- '%s\n' "$str"
fi
# vi:ft=sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment