Canonicalize CIDR: Difference between revisions

Content deleted Content added
PureFox (talk | contribs)
→‎{{header|Go}}: Changed to cope with the extra examples.
Petelomax (talk | contribs)
Line 333: Line 333:
<pre>$ canonicalize_cidr.pl 87.70.141.1/22
<pre>$ canonicalize_cidr.pl 87.70.141.1/22
87.70.140.0/22</pre>
87.70.140.0/22</pre>

=={{header|Phix}}==
<lang Phix>function canonicalize_cidr(string cidr)
cidr = substitute(cidr,"."," ") -- (else %d eats 0.0 etc)
if not find('/',cidr) then cidr &= "/32" end if
sequence res = scanf(cidr,"%d %d %d %d/%d")
if length(res)=1 then
integer {a,b,c,d,m} = res[1]
if a>=0 and a<=255
and b>=0 and b<=255
and c>=0 and c<=255
and d>=0 and d<=255
and m>=1 and m<=32 then
atom mask = power(2,32-m)-1,
addr = bytes_to_int({d,c,b,a})
addr -= and_bits(addr,mask)
{d,c,b,a} = int_to_bytes(addr)
return sprintf("%d.%d.%d.%d/%d",{a,b,c,d,m})
end if
end if
return "???"
end function

constant tests = {"87.70.141.1/22",
"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 i=1 to length(tests) do
string ti = tests[i]
printf(1,"%-18s -> %s\n",{ti,canonicalize_cidr(ti)})
end for</lang>
{{out}}
<pre>
87.70.141.1/22 -> 87.70.140.0/22
36.18.154.103/12 -> 36.16.0.0/12
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>


=={{header|Python}}==
=={{header|Python}}==