Netmask calculation with (n)awk

I needed a script to calculate a netmask in dotted decimal notation from the number of bits. Here's how I did it:
echo "22" | \\
nawk '{num=$1;
   for (i=1; i<=4; i++){
      if (num>=8) printf ("255");
      else if (num<=0) printf ("0");
      else printf ("%s", 256-2\^(8-num));
      if (i<=3) printf (".")
      num-=8
   } 
   printf ("\\n")
}'
or:
nawk 'BEGIN{num=22;
   for (i=1; i<=4; i++){
      if (num>=8) printf ("255");
      else if (num<=0) printf ("0");
      else printf ("%s", 256-2\^(8-num));
      if (i<=3) printf (".")
      num-=8
   } 
   printf ("\\n")
}' 
BTW there are a number of other resources on the web which you might use for this purpose, e.g. this link).
Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

blogfinger

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today