Skip to content

Instantly share code, notes, and snippets.

@Sitwon
Last active December 31, 2015 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sitwon/7935295 to your computer and use it in GitHub Desktop.
Save Sitwon/7935295 to your computer and use it in GitHub Desktop.
A function for converting mask bits to a mask address. For example: 32 => 255.255.255.255 24 => 255.255.255.0 22 => 255.255.252.0
#!/bin/bash
bitsToMask(){
trace_log "bitsToMask" "$@"
if [ "$#" -eq 1 ]; then
bitsToMask "${1}" 0 ""
elif [ "${2}" -eq 4 ]; then
echo "${3%.}"
else
local BITS=${1}
local COUNT=${2}
local ADDR=${3}
(( COUNT++ ))
if [ "${BITS}" -ge 8 ]; then
ADDR="${ADDR}255."
(( BITS -= 8 ))
else
local ADDR_SEGMENT="$( bc <<<"256 - 2 ^ ( 8 - ${BITS} )" )."
ADDR="${ADDR}${ADDR_SEGMENT}"
BITS=0
fi
bitsToMask "${BITS}" "${COUNT}" "${ADDR}"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment