Canonicalize CIDR: Difference between revisions
→{{header|Wren}}: Changed to cope with the extra examples.
m (→{{header|REXX}}: changed a comment, updated example nodes.) |
(→{{header|Wren}}: Changed to cope with the extra examples.) |
||
Line 522:
{{libheader|Wren-fmt}}
{{libheader|Wren-str}}
<lang ecmascript>import "
import "/str" for Str
// canonicalize a CIDR block: make sure none of the host bits are set
var
// dotted-decimal / bits in network part▼
var split = cidr.split("/")▼
var dotted = split[0]▼
var size = Num.fromString(split[1])▼
// get IP as binary string▼
▲// dotted-decimal / bits in network part
var binary = dotted.split(".").map { |n| Fmt.swrite("$08b", Num.fromString(n)) }.join()
▲var split = cidr.split("/")
▲var dotted = split[0]
▲var size = Num.fromString(split[1])
// replace the host part with all zeros▼
▲// get IP as binary string
// convert back to dotted-decimal▼
▲// replace the host part with all zeros
var chunks = Str.chunks(binary, 8)▼
var canon = chunks.map { |c| Conv.atoi(c, 2) }.join(".")▼
▲// convert back to dotted-decimal
▲var chunks = Str.chunks(binary, 8)
}
▲var canon = chunks.map { |c| Conv.atoi(c, 2) }.join(".")
var tests = [
▲// and output
▲System.print(canon + "/" + split[1])</lang>
"36.18.154.103/12",
"62.62.197.11/29",
"67.137.119.181/4",
"161.214.74.21/24" ,
"184.232.176.184/18"
]
for (test in tests) {
Fmt.print("$-18s -> $s", test, canonicalize.call(test))
}</lang>
{{out}}
<pre>
36.18.154.103/12 -> 36.16.0.0/12
▲87.70.140.0/22
62.62.197.11/29 -> 62.62.197.8/29
67.137.119.181/4 -> 64.0.0.0/4
161.214.74.21/24 -> 161.214.74.0/24
184.232.176.184/18 -> 184.232.128.0/18
</pre>
|