Skip to content

Instantly share code, notes, and snippets.

@GregTonoski
Created July 6, 2023 15:32
Show Gist options
  • Save GregTonoski/353d0d27650331044ba0a1ca170721fa to your computer and use it in GitHub Desktop.
Save GregTonoski/353d0d27650331044ba0a1ca170721fa to your computer and use it in GitHub Desktop.
Convert a hexadecimal string to bytes.
#!/bin/bash
# hex_string_to_bytes.bash: convert a hexadecimal string to bytes.
# Examples:
# $ bash hex_string_to_bytes FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140
# $ bash hex_string_to_bytes FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140 > output_file.bin
export LC_ALL=C
hex_string="$1"
#######################################
# Input validation - only hexadecimal characters permitted
#######################################
case ${hex_string} in
''|*[^[:xdigit:]]*) echo "The string contains characters that don't belong to hexadecimal set. The program execution is terminated."; exit 1;;
*) ;;
esac
# The equivalent of the above case command except less portable.
# if ! [[ "${hex_string}" =~ ^[[:xdigit:]]+$ ]]; then
# continue
# else
# exit 1
# fi
#######################################
# Input validation - even number of characters is required
#######################################
if (( ${#hex_string} % 2 )); then
echo "The number of characters is invalid and doesn't translate to whole bytes."
exit 1
fi
for ((i=0; i<${#hex_string}; i+=2)); do
printf "%b" "\x${hex_string:i:2}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment