Skip to content

Instantly share code, notes, and snippets.

@hongkongkiwi
Last active May 6, 2022 04:18
Show Gist options
  • Save hongkongkiwi/02d8bcde0c810f8dff6b6a96d11ce6bd to your computer and use it in GitHub Desktop.
Save hongkongkiwi/02d8bcde0c810f8dff6b6a96d11ce6bd to your computer and use it in GitHub Desktop.
Simple shell scripts to convert decimal to hex in bash (and visa versa) with various formatting options
#!/bin/bash -ue
##
# Simple shell script to convert decimal to hex
# Created by hongkongkiwi: https://gist.github.com/hongkongkiwi/02d8bcde0c810f8dff6b6a96d11ce6bd
# Usage:
# ./dec_hex "12356"
# ./dec_hex -n "12356"
# ./dec_hex -n -l "12356"
# ./dec_hex -n -l -o "12356"
##
HELP="$0 [-n|--no-leading] [-o|--hex-only] [-l|--lowercase] <integer>"
NO_LEADING=""
HEX_ONLY=""
LOWERCASE=""
for ARG in $@; do
case "$ARG" in
'-n'|'--no-leading') NO_LEADING="yes";;
'-o'|'--hex-only') HEX_ONLY="yes";;
'-l'|'--lowercase') LOWERCASE="yes";;
'-h'|'--help') echo >&2 "$HELP"; exit 255;;
esac
# Number is always last arg
NUM="$ARG"
done
if ! [[ "$NUM" =~ ^[0-9]+$ ]]; then
echo >&2 "ERROR: pass a decimal integer"; echo >&2 "$HELP"; exit 255;
fi
if [ -n "$NO_LEADING" ]; then
# Strip off leading zeros as printf does not like it
NUM="$(echo "$NUM" | sed 's|^[0]*||g')"
OUTPUT="$(printf "%x\n" "$NUM")"
else
# Strip everything but leading zeros
LEADING="$(echo "$NUM" | sed -n 's/^\([0]*\)[0-9]\+/\1/p')"
# Strip off leading zeros as printf does not like it
NUM="$(echo "$NUM" | sed 's|^[0]*||g')"
OUTPUT="$(printf "${LEADING}%x\n" "$NUM")"
fi
if [ -n "$LOWERCASE" ]; then
OUTPUT="$(echo "$OUTPUT" | tr '[:upper:]' '[:lower:]')"
else
OUTPUT="$(echo "$OUTPUT" | tr '[:lower:]' '[:upper:]')"
fi
if [ -n "$HEX_ONLY" ]; then
echo "$OUTPUT"
else
echo "0x$OUTPUT"
fi
exit 0
#!/bin/bash -ue
command -v "dc" >/dev/null 2>&1 || { echo >&2 "I require dc but it's not installed. Aborting."; exit 1; }
TOTAL_HEX="00000"
for HEX_NUM in $@; do
TOTAL_HEX="$(echo "$TOTAL_HEX" "${HEX_NUM#"0x"}" | dc -e '16o16i?+p')"
done
echo "0x$TOTAL_HEX"
#!/bin/bash -ue
[ -n "${1-}" ] || { echo >&2 "ERROR: pass a hex number"; exit 255; }
printf "%d\n" "0x${1#"0x"}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment