Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CIDR to netmask conversion in javascript

Tags:

javascript

php

I found some code in PHP to convert CIDR to netmask.

function createNetmaskAddr($bitcount) {
   $netmask = str_split(str_pad(str_pad('', $bitcount, '1'), 32, '0'), 8);
   foreach ($netmask as &$element) $element = bindec($element);
   return join('.', $netmask);
}

Is it possible to do it in javascript?

Unfortunately I have no experience in javascript.

like image 954
Oualid Avatar asked Feb 20 '14 09:02

Oualid


1 Answers

Try this:

function createNetmaskAddr(bitCount) {
  var mask = [], i, n;
  for(i=0; i<4; i++) {
    n = Math.min(bitCount, 8);
    mask.push(256 - Math.pow(2, 8-n));
    bitCount -= n;
  }
  return mask.join('.');
}
like image 136
ziollek Avatar answered Oct 03 '22 14:10

ziollek