Version 0 of Playing with bits

Updated 2002-12-09 07:56:07

if 0 { Richard Suchenwirth 2002-12-07 - Here is another educational Tcltoy: a set of 8 checkboxes that represent the bits of a byte. Each is labeled with its positional value below. The button at bottom displays the current value of the byte in hexadecimal, octal and decimal. Clicking on it resets all bits to 0, or, if they already are, to 1.

The simple code below contains some tricks that are unique to Tcl. The positional values of the 8 bits serve as variable names as well, and with prefixed "." as widget names of the checkboxes. The two procedures first import the global list of positional values, then via eval global each of them separately. As name and onvalue of a "bit" are the same, the otherwise puzzling command

 set $i $i

makes perfect sense - if i is 16, it assigns the value 16 to the variable 16... }

 set positionalValues {128 64 32 16 8 4 2 1}
 foreach i $positionalValues {
    checkbutton .$i -variable $i -onvalue $i -command compute
    lappend buttons .$i
    lappend labels [label .l$i -text $i]
 }
 eval grid $buttons
 eval grid $labels
 button .result -textvar result -command reset -borderwidth 1
 grid .result -columnspan 8 -sticky ew

 proc reset {} {
    global positionalValues result
    eval global $positionalValues
    foreach i $positionalValues {
        if {[lindex $result end] == 0} {
            set $i $i
        } else {set $i 0}
    }
    compute
 }
 proc compute {} {
    global positionalValues result
    eval global $positionalValues
    set res 0
    foreach i $positionalValues {
        incr res [set $i]
    }
    set result [format "Hex: 0x%2X, Octal: 0%3.3o, Decimal: %d" $res $res $res]
 }
 compute ;# show the initial state (should be 0)
 bind . <Escape> {exec wish $argv0 &; exit}