Created
March 26, 2014 05:31
-
-
Save orchid-hybrid/9777370 to your computer and use it in GitHub Desktop.
GUI to convert between hexadecimal, decimal and binary numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/wish | |
package require Tk | |
wm title . "numb" | |
grid [ttk::frame .c -padding "3 3 12 12"] -column 0 -row 0 -sticky nwes | |
grid columnconfigure . 0 -weight 1 | |
grid rowconfigure . 0 -weight 1 | |
grid [ttk::label .c.hexl -text "hexadecimal"] -column 1 -row 1 -sticky e | |
grid [ttk::entry .c.hexf -width 32 -textvariable hex] -column 2 -row 1 -sticky w | |
grid [ttk::label .c.decl -text "decimal"] -column 1 -row 2 -sticky e | |
grid [ttk::entry .c.decf -width 32 -textvariable dec] -column 2 -row 2 -sticky w | |
grid [ttk::label .c.binl -text "binary"] -column 1 -row 3 -sticky e | |
grid [ttk::entry .c.binf -width 32 -textvariable bin] -column 2 -row 3 -sticky w | |
grid [ttk::button .c.calc -text "Quit" -command exit] -column 2 -row 4 -sticky e | |
foreach w [winfo children .c] {grid configure $w -padx 3 -pady 3} | |
bind .c.hexf <Return> {set dec [hex2dec $hex]; set bin [dec2bin $dec]} | |
bind .c.decf <Return> {set hex [dec2hex $dec]; set bin [dec2bin $dec]} | |
bind .c.binf <Return> {set dec [bin2dec $bin]; set hex [dec2hex $dec]} | |
# http://wiki.tcl.tk/1591 | |
# http://wiki.tcl.tk/3242 | |
proc dec2hex {decimalNumber} { | |
format %04X $decimalNumber | |
} | |
proc hex2dec {largeHex} { | |
set res 0 | |
foreach hexDigit [split $largeHex {}] { | |
set new 0x$hexDigit | |
set res [expr {16*$res + $new}] | |
} | |
return $res | |
} | |
proc dec2bin {i} { | |
#returns a string, e.g. dec2bin 10 => 1010 | |
set res {} | |
while {$i>0} { | |
set res [expr {$i%2}]$res | |
set i [expr {$i/2}] | |
} | |
if {$res == {}} {set res 0} | |
return $res | |
} | |
proc bin2dec {bin} { | |
if {$bin == 0} { | |
return 0 | |
} elseif {[string match -* $bin]} { | |
set sign - | |
set bin [string range $bin 1 end] | |
} else { | |
set sign {} | |
} | |
if {[string map [list 1 {} 0 {}] $bin] ne {}} { | |
error "argument is not in base 2: $bin" | |
} | |
set r 0 | |
foreach d [split $bin {}] { | |
incr r $r | |
incr r $d | |
} | |
return $sign$r | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment