Canonicalize CIDR: Difference between revisions

→‎String manipulation: Add more examples, streamline code
(→‎{{header|UNIX Shell}}: Add implementation)
(→‎String manipulation: Add more examples, streamline code)
Line 1,310:
{{trans|Perl}}
<lang perl6>#!/usr/bin/env raku
unit sub MAIN(*@cidrs);
 
if (!@*ARGS)cidrs {
# canonicalize a CIDR block: make sure none of the host bits are set
# test data
if (!@*ARGS) {
@cidrs = «87.70.141.1 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»;
@*ARGS = $*IN.lines;
}
 
for @*ARGScidrs -> $cidr {
say "$cidr -> $(canonicalize $cidr)";
}
 
# canonicalize a CIDR block: make sure none of the host bits are set
sub canonicalize($cidr) {
# dotted-decimal / bits in network part
my ($dotted, $size) = $cidr.split(: '/');
 
# get network part of the IP as binary string
my $binary = $dotted.split('.').map(*».fmt("'%08b")').join.substr(0, $size);
 
# Replace theAdd host part with all zeroes
$binary.substr-rw($size) ~= 0 x (32 - $size);
 
# Convert back to dotted-decimal
my $canon = $binary.comb(8).map(*.join».parse-base(2)).join(: '.');
 
# And output
Line 1,335 ⟶ 1,340:
 
{{Out}}
<pre>$ canonicalize_cidr.raku 87.70.141.1/22 -> 87.70.140.0/22
36.18.154.103/12 -> 36.16.0.0/12
87.70.140.0/22</pre>
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>
 
===Bit mask and shift===
1,480

edits