Canonicalize CIDR: Difference between revisions

Content added Content deleted
(Added Wren)
Line 183: Line 183:
<pre>$ canonicalize_cidr.rb 87.70.141.1/22
<pre>$ canonicalize_cidr.rb 87.70.141.1/22
87.70.140.0/22</pre>
87.70.140.0/22</pre>

=={{header|Wren}}==
{{trans|Ruby}}
{{libheader|Wren-fmt}}
{{libheader|Wren-str}}
<lang ecmascript>import "os" for Process
import "/fmt" for Fmt, Conv
import "/str" for Str

// canonicalize a CIDR block: make sure none of the host bits are set
var args = Process.arguments
var cidr = (args.count > 0) ? args[0] : Fiber.abort("Please pass the CIDR to be canonicalized.")

// 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
var binary = dotted.split(".").map { |n| Fmt.swrite("$08b", Num.fromString(n)) }.join()

// replace the host part with all zeros
binary = binary[0...size] + "0" * (32 - size)

// convert back to dotted-decimal
var chunks = Str.chunks(binary, 8)
var canon = chunks.map { |c| Conv.atoi(c, 2) }.join(".")

// and output
System.print(canon + "/" + split[1])</lang>

{{out}}
<pre>
$ wren canonicalize_cidr.wren 87.70.141.1/22
87.70.140.0/22
</pre>