2021-06-29

Swap Nibbles

You are given a positive integer $N.

Write a script to swap the two nibbles of the binary representation of the given number and print the decimal number of the new binary representation.

To keep the task simple, we only allow integer less than or equal to 255.

#!/usr/bin/env tclsh
#
# You are given a positive integer $N.
# Write a script to swap the two nibbles of the binary representation of the 
# given number and print the decimal number of the new binary representation.
# To keep the task simple, we only allow integer less than or equal to 255.
#
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 number1 [format %04b [expr $number & 0xf]]
set number2 [format %04b [expr ($number >> 4) & 0xf]]
puts [format "%d" 0b$number1$number2]

沒有留言: