2021-07-16

Invert Bit

You are given integers 0 <= $m <= 255 and 1 <= $n <= 8.

Write a script to invert $n bit from the end of the binary representation of $m and print the decimal representation of the new binary number.

#!/usr/bin/env tclsh

if {$argc >= 2} {
    set m [lindex $argv 0]
    set n [lindex $argv 1]
} else {
    puts "Please input two numbers, m and n."
    exit    
}

if {$m < 0 || $m > 255} {
    puts "Number requires 0 <= M <= 255"
    exit
}

if {$n < 1 || $n > 8} {
    puts "Number requires 1 <= N <= 8"
    exit
}

set bnumber [format %08b $m]
set string1 ""
set string3 ""
set string2 [string index $bnumber [expr 8 - $n]]
if {$n < 8} {
    set string1 [string range $bnumber 0 [expr 8 - $n - 1]]
}
if {$n > 1} {
    set string3 [string range $bnumber [expr 8 - $n + 1] end]
}

if {[string compare $string2 "1"]==0} {
    set result [string cat $string1 "0" $string3]
} else {
    set result [string cat $string1 "1" $string3]
}

puts [format "%d" 0b$result]

沒有留言: