You are given a positive integer $N less than or equal to 255.
Write a script to swap the odd positioned bit with even positioned bit and print the decimal equivalent of the new binary representation.
#!/usr/bin/env tclsh
if {$argc >= 1} {
set number [lindex $argv 0]
} elseif {$argc == 0} {
puts "Please input a number"
exit
}
if {$number <=0 || $number > 255} {
puts "Number requires 0 < N <= 255"
exit
}
set bnumber [format %08b $number]
set length [string length $bnumber]
set answer ""
for {set i 0} {$i < $length} {incr i 2} {
set n1 [string index $bnumber $i]
set n2 [string index $bnumber [expr $i + 1]]
set answer [string cat $answer $n2 $n1]
}
puts [format "%d" 0b$answer]
沒有留言:
張貼留言