Need every binary IP octet to contain eight digits? String.prototype.padStart adds filler to the beginning of a string until it reaches a target length. If you omit the filler, it uses a space. section 6.2
Keep these behavior rules in mind:
- The first argument is the target length; the second is the filler string. section 6.2
- A multi-character filler repeats as needed, then is truncated if it cannot fit evenly. section 6.2
- If the original string already meets or exceeds the target length, it is returned without padding. section 6.2
Pad binary octets
Number(octet).toString(2).padStart(8, '0') converts an octet to binary, then adds leading zeros to reach eight characters. For example, the binary value 10 becomes 00000010. Applying this to each octet produces a consistently padded binary IP address. section 6.2
function binaryIP(decimalIPStr) {
return decimalIPStr.split('.').map(function(octet) {
return Number(octet).toString(2).padStart(8, '0')
}).join('.');
}
binaryIP('192.168.2.1'); 1
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":6,\"ch\":10},{\"line\":6,\"ch\":11}]]"}
!@%STYLE%@!
See padStart used in the complete binary IP conversion function. section 6.2
