I have a subnet mask as a value in an object. It comes in the long form, ie. 255.255.255.0 (for /24).
I haven't come across some sort of JavaScript function for calculating this. So before I write a whole lot of if
and else if
statements, I want to quickly double check to make sure that I didn't miss out on some JavaScript goody that does this already.
Thanks!
Edit: Clarification
I was wondering if there is a JavaScript function that I don't know of, that will translate the long form and return a short form, slash notation. For Example:
If I pass var obj_mask = "255.255.255.0";
to a existing JavaScript (API?), it will return a /24
value.
If such function doesn't exist in JavaScript, it's fine, I have already written half the if
statements, and I'll be happy to share it after so no one else has to write it out. But seeing that I'm new to JS, I wanted to know if such function/API existed natively to the language.
I use the following functions for netmask to CIDR and CIDR to netmask conversions:
var netmask2CIDR = (netmask) => (netmask.split('.').map(Number)
.map(part => (part >>> 0).toString(2))
.join('')).split('1').length -1;
var CIDR2netmask = (bitCount) => {
var mask=[];
for(var i=0;i<4;i++) {
var n = Math.min(bitCount, 8);
mask.push(256 - Math.pow(2, 8-n));
bitCount -= n;
}
return mask.join('.');
}
Hope this helps!