#!/bin/bash
#
# netmask_convert
#
#

function short2addr()
{
    # /24 -> 255.255.255.0
    local full
    local mask=${1#/}
    local t1 t2 t3 t4

    #
    # get inter representation of /X
    #
    full=0; 
    for i in $(seq 1 31); do 
        if [ $mask -gt 0 ]; then 
            (( full++)); 
        fi; 
        (( full = full << 1 ));  
        (( mask-- )); 
    done; 
    (( t1 = full / ( 2 ** 24 )  ));
    (( full = full - ( t1 << 24 ) ))
    (( t2 = full / ( 2 ** 16 )  )); 
    (( full = full - ( t2 << 16 ) ))
    (( t3 = full / ( 2 ** 8 )  )); 
    (( full = full - ( t3 << 8 ) ))
    (( t4 = full  )); 

    printf "%s.%s.%s.%s\n" "$t1" "$t2" "$t3" "$t4"
}

function addr2short()
{
    # 255.255.255.0 -> /24
    local full
    local addr=$1
    local t1 t2 t3 t4
    local bit mask=0
    t1=${addr%%.*}; addr=${addr#*.}
    t2=${addr%%.*}; addr=${addr#*.}
    t3=${addr%%.*}; addr=${addr#*.}
    t4=${addr}
    #echo $t1 $t2 $t3 $t4 
    (( full= ( t1 << 24 ) + ( t2 << 16 ) + ( t3 << 8 ) + t4 ))
    #echo $full
    for i in $( seq 31 -1 0 ); do 
        (( bit = full >> $i ))
        (( full = full - ( bit << $i ) ))
        if [ $bit -eq 1 ]; then
           (( mask++ ))
        else 
           break
        fi
    done
    printf "/%s\n" $mask
}


#short2addr /3 ; echo
#short2addr 23; echo
#short2addr 24 ; echo
#short2addr 27 ; echo
#
#addr2short 255.128.0.0; echo
#addr2short 255.255.255.128; echo

case "$1" in
   *.*.*.* ) addr2short "$1"
             ;;
    /* | [0-9] | [0-3][0-9] ) short2addr "$1" 
             ;;
esac
