一、练习

1.二进制转十进制

proc b2d {b} {
set sum ;set len [string length $b]
for {set i } {$i<$len} {incr i} {
incr sum [expr int([string index $b $i]*pow(,$len-$i-))]
}
return $sum
}

2.十进制转二进制

proc d2b {d} {
set b ""
while {$d!=} {
set b "[expr $d%2]$b"
set d [expr $d/]
}
return $b
}

3.根据长度转换成子网掩码

proc len2mask {len} {
set mask ""
for {set i } {$i<} {incr i} {
if {$len>=} {
lappend mask [b2d [formatb ]]
incr len -
} else {
lappend mask [b2d [formatb $len ]]
set len
}
}
return [join $mask .]
}

4.根据子网掩码转换成长度

proc mask2len {mask} {
set msks [split $mask .]
set len
for {set i } {$i<} {incr i} {
set m [lindex $msks $i]
set str [d2b $m]
incr len [string length [string trim $str ]]
}
return $len
}
05-06 06:36