Last active
November 8, 2021 20:14
-
-
Save Reinis/955ce18610d6e499819a56d7a8ae75e1 to your computer and use it in GitHub Desktop.
Print bit pattern of a number in Bash
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
# Pretty print binary pattern of a number | |
pb() { | |
pn 2 4 "${1}" | |
} | |
# Pretty print octal value of a number | |
po() { | |
pn 8 3 "${1}" | |
} | |
# Pretty print hexadecimal value of a number | |
ph() { | |
pn 16 2 "${1}" | tr '[:upper:]' '[:lower:]' | |
} | |
# Pretty print denary value of a number | |
pd() { | |
pn 10 3 "${1}" | sed -E 's/^0+//' | |
} | |
# Print encoded text in hexadecimal | |
pe() { | |
echo 0x$(echo -n ${1} | xxd -p) | |
} | |
# Pretty print value of a number in given base and chomp | |
# $ pn base chomp number | |
# 0xxx xxxx xxxx | |
# ^ ^ ^ ^ | |
# | | chomp size | |
# | space | |
# prefix | |
pn() { | |
local b=${1} # base | |
local c=${2} # chomp size | |
local n=0 # number | |
local r=0 # remainder (prefix size) | |
local u=${2} # unit size | |
# There are 8 bits in a byte | |
if [[ "${b}" == 2 ]]; then | |
u=8 | |
fi | |
# Mathch decimal, octal (0123), hexadecimal (0xabcd) or base 2-64 number (2#10101010) | |
if [[ "${3}" =~ ^(-)?([[:digit:]]+|0x[[:xdigit:]]+|[2-9][0-9]?#[0-9a-zA-Z@_]+)$ ]]; then | |
# number | |
n=$(printf '%X' $((${3}))) # To properly handle negative numbers | |
elif [[ "${#3}" == 1 ]]; then | |
# character | |
n=$(printf '%X' "'${3}") | |
else | |
echo "Error: Can print only one number or character! (Received: ${3})" | |
return 1 | |
fi | |
n=$(bc <<< "obase=${b}; ibase=16; ${n}") | |
r=$(( ${#n} % ${u} )) | |
[[ ${r} == 0 ]] || r=$((${u} - ${r})) | |
for i in $(seq ${r}); do | |
n=$(sed 's/^/0/' <<< "${n}") | |
done | |
if [[ "${c}" > 0 ]]; then | |
n=$(sed -E ":a s/([[:xdigit:]]+)([^ ]{${c}})/\1 \2/;ta" <<< "${n}") | |
fi | |
echo ${n} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment