title: how to convert total number of hosts in network to mask?
body: <p>how can i convert the total number of hosts in a network to mask?</p>
  
  <p>for example, <code>1024</code> to <code>/22</code></p>
  
  <p><code>ip calc</code> can do the opposite</p>
  
  <pre><code>$ ipcalc 89.150.4.0/22
  
  Address:   89.150.4.0           01011001.10010110.000001 00.00000000
  Netmask:   255.255.252.0 = 22   11111111.11111111.111111 00.00000000
  Wildcard:  0.0.3.255            00000000.00000000.000000 11.11111111
  =&gt;
  Network:   89.150.4.0/22        01011001.10010110.000001 00.00000000
  HostMin:   89.150.4.1           01011001.10010110.000001 00.00000001
  HostMax:   89.150.7.254         01011001.10010110.000001 11.11111110
  Broadcast: 89.150.7.255         01011001.10010110.000001 11.11111111
  Hosts/Net: 1022                 Class A
  </code></pre>
  
  <hr>
  
  <p>background information:</p>
  
  <p>i have a text file with content like</p>
  
  <pre><code>AD|85.94.160.0|8192
  AD|89.150.2.0|512
  AD|89.150.4.0|1024
  AD|89.150.8.0|2048
  </code></pre>
  
  <p>and i need to convert the 3rd column (total number of hosts) to network mask</p>
  
  <p>if it's not possible using shell tools, i don't mind piping it to a python/perl/ruby script</p>
  
  <hr>
  
  <p>EDIT</p>
  
  <p>very concise answer and comments from @KamilCuk helped me understand the logic behind it.<br>
  i'm not even using <code>ipcalc</code> for that anymore :)</p>
  
  <p>THE ANSWER</p>
  
  <p><strong>from <code>hosts</code> to <code>mask</code></strong></p>
  
  <pre><code>$: HOSTS=1024
  $: LC_NUMERIC=C printf "%.0f" $(bc -l &lt;&lt;&lt; "32-(l($HOSTS)/l(2))")
  
  22
  </code></pre>
  
  <p>or</p>
  
  <pre><code>$: HOSTS=1024
  $: echo | awk -v HOSTS=$HOSTS '{print int(32-(log(HOSTS)/log(2)))}'
  
  22
  </code></pre>
  
  <p><strong>and from <code>mask</code> to <code>hosts</code></strong></p>
  
  <pre><code>$: MASK=22
  $: echo "2^(32-$MASK)" | bc
  
  1024
  </code></pre>
  
  <p>or</p>
  
  <pre><code>$: MASK=22
  $: echo | awk -v MASK=$MASK '{print 2^(32-MASK)}'
  
  1024
  </code></pre>