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 "os/fmt" for ProcessFmt, Conv
import "/fmt" for Fmt, Conv
import "/str" for Str
 
// canonicalize a CIDR block: make sure none of the host bits are set
var argscanonicalize = ProcessFn.argumentsnew { |cidr|
// dotted-decimal / bits in network part
var cidr = (args.count > 0) ? args[0] : Fiber.abort("Please pass the CIDR to be canonicalized.")
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
var binary = dottedbinary[0.split(".").mapsize] {+ |n| Fmt.swrite("$08b0", Num.fromString* (n))32 }.join(- size)
 
// convert back to dotted-decimal
// replace the host part with all zeros
var chunks = Str.chunks(binary, 8)
binary = binary[0...size] + "0" * (32 - size)
var canon = chunks.map { |c| Conv.atoi(c, 2) }.join(".")
 
// and outputreturn
// convert back to dotted-decimal
System.print( return canon + "/" + split[1])</lang>
var chunks = Str.chunks(binary, 8)
}
var canon = chunks.map { |c| Conv.atoi(c, 2) }.join(".")
 
var tests = [
// and output
"87.70.140141.01/22",
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>
$87.70.141.1/22 wren canonicalize_cidr.wren -> 87.70.141140.10/22
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>
9,490

edits