since all the 1's
in a subnet mask are grouped together at the high side, there's absolutely no need to pre-make any of the binary-bit-strings, since "counting leading edge 1's"` is same as
1. 2^32 (or simply : ( 4 ^ 4 ) ^ 4 )
minus
integer of subnet mask bits
2. take the log-base-2 value of step-1, which gives you
# of 0-bits at the bottom
(a tiny 2^-16 has been padded for error-correction), and
3. finally, return `32 minus value of step-2`
— tested and confirmed working on mawk
, gawk
, and nawk
mawk '
function _____(__,_,___,____) {
return \
substr(___="[.]" (_=""), __~("["(+_)".]"(+_)) \
? sub("^"(+_)"+",_,__) + gsub(___ (+_)"+",".",__):_,_) \
"subnet-mask::/" (int(\
log(-(__=____[_ =__ = split(__,____,___)] \
+ (___=_^=_+!--__) * ____[__] \
+ (___ ^= --__) * ____[__] \
+ ____[_^!_]*_*___) + ___^(_+=_^=_<_)\
) / -log(_) - _^-_^_^_) \
+ _^_^_*_)
}
BEGIN { CONVFMT = "%.250g"
_+= _^= OFMT = "%.25g"
}
($++NF = _____($_))^!_'
- 1st column is reference answer
- 2nd column the
IPv4
-equivalent of that subnet mask, and
- 3rd column the calculated one via the function
/0 000.000.000.000 subnet-mask::/0 # this line only included for completeness
/1 128.000.000.000 subnet-mask::/1
/2 192.000.000.000 subnet-mask::/2
/3 224.000.000.000 subnet-mask::/3
/4 240.000.000.000 subnet-mask::/4
/5 248.000.000.000 subnet-mask::/5
/6 252.000.000.000 subnet-mask::/6
/7 254.000.000.000 subnet-mask::/7
/8 255.000.000.000 subnet-mask::/8
/9 255.128.000.000 subnet-mask::/9
/10 255.192.000.000 subnet-mask::/10
/11 255.224.000.000 subnet-mask::/11
/12 255.240.000.000 subnet-mask::/12
/13 255.248.000.000 subnet-mask::/13
/14 255.252.000.000 subnet-mask::/14
/15 255.254.000.000 subnet-mask::/15
/16 255.255.000.000 subnet-mask::/16
/17 255.255.128.000 subnet-mask::/17
/18 255.255.192.000 subnet-mask::/18
/19 255.255.224.000 subnet-mask::/19
/20 255.255.240.000 subnet-mask::/20
/21 255.255.248.000 subnet-mask::/21
/22 255.255.252.000 subnet-mask::/22
/23 255.255.254.000 subnet-mask::/23
/24 255.255.255.000 subnet-mask::/24
/25 255.255.255.128 subnet-mask::/25
/26 255.255.255.192 subnet-mask::/26
/27 255.255.255.224 subnet-mask::/27
/28 255.255.255.240 subnet-mask::/28
/29 255.255.255.248 subnet-mask::/29
/30 255.255.255.252 subnet-mask::/30
/31 255.255.255.254 subnet-mask::/31