Welcome, guest | Sign In | My Account | Store | Cart

The command adds two numbers in any base that can be expressed as a string of unique symbols. From Jeff Hobbs's bag of utilities, original author is John Ellson <ellson@lucent.com>.

Tcl, 46 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
variable symbols 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

proc add_baseX {numA numB} {
    # add two numbers in any base that can be expressed as a string of 
    # unique symbols
    #
    # John Ellson <ellson@lucent.com>

    variable symbols
    set base [string length $symbols]
    set idxA [string length $numA]
    set idxB [string length $numB]
    set carry 0
    set result ""
    while {$idxA || $idxB || $carry} {
	if {$idxA} {
	    set digA [string index $numA [incr idxA -1]]
	    set decA [string first $digA $symbols]
	    if {$decA < 0} {
		puts stderr "invalid digit \"$digA\""
		return -1
	    }
	} else {
	    set decA 0
	}
	if {$idxB} {
	    set digB [string index $numB [incr idxB -1]]
	    set decB [string first $digB $symbols]
	    if {$decB < 0} {
		puts stderr "invalid digit \"$digB\""
		return -1
	    }
	} else {
	    set decB 0
	}
	set sumdec [expr {$decA + $decB + $carry}]
	if {$sumdec >= $base} {
	    set carry 1
	    incr sumdec -$base
	} else {
	    set carry 0
	}
	set result [string index $symbols $sumdec]$result
    }
    return $result
}  

The code is effectively configured by the namespace variable 'symbols', which contains the alphabet of symbols to use by the adder.

Created by andreas kupries on Thu, 22 Aug 2002 (MIT)
Tcl recipes (162)
andreas kupries's recipes (20)

Required Modules

  • (none specified)

Other Information and Tasks