Skip to content

Instantly share code, notes, and snippets.

@p120ph37
Created July 7, 2015 21:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save p120ph37/015941a57f0d8f9a1722 to your computer and use it in GitHub Desktop.
Save p120ph37/015941a57f0d8f9a1722 to your computer and use it in GitHub Desktop.
Base64 decode purely via Bash builtins.
#!/bin/sh
((V=N=0))
while :; do
((V<<=6,++N))
IFS= read -n1 C && {
printf -vC '%d' "'$C"
((C=C>64&&C<91?C-65:C>96&&C<123?C-71:C>47&&C<58?C+4:C==43?62:C==47?63:(V>>=6,--N,0),V|=C))
}
((N==4)) && {
for((N-=2;N>=0;--N)); do
printf `printf '\\\\x%02X' $((V>>N*8&255))`
done
[ -z "$C" ] && break
((V=N=0))
}
done
# one-liner:
# d64(){ local N=0 V=0 C;while :;do((V<<=6,++N));IFS= read -n1 C&&{ printf -vC '%d' "'$C";((C=C>64&&C<91?C-65:C>96&&C<123?C-71:C>47&&C<58?C+4:C==43?62:C==47?63:(V>>=6,--N,0),V|=C));};((N==4))&&{ for((N-=2;N>=0;--N));do printf `printf '\\\\x%02X' $((V>>N*8&255))`;done;[ -z "$C" ]&&break;((V=N=0));};done;}
#
# tests:
# echo 'aGVsbG8hCg==' | d64
# echo 'aGVsbG8hIQo=' | d64
# echo 'aGVsbG8hISEK' | d64
# echo 'aGVsbG8hISEhCg==' | d64
# echo 'aGVs bG8h Cg===' | d64
# echo 'aGV sbG8 hCg' | d64
# echo "YWE\@+\nYmI/:\[\{\!Cg" | d64
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment