Updated 2012-11-20 11:43:00 by RLE

Richard Suchenwirth 2006-12-06 - Here's a way of converting an ASCII string of up to 9 characters from and to a wide integer, in which a sequence of 7 bits corresponds to one character. 7*9 = 63, so the integers will always be non-negative, as the sign bit is always 0:
 proc base128'encode str {
    if {[string length $str]>9} {error "string must be 0..9 characters long"}
    set res 0
    foreach c [split $str ""] {
        set res [expr {wide($res)<<7 | [scan $c %c]%128}]
    }
    set res
 }
 proc base128'decode int {
    set res ""
    while {$int != 0} {
        set res [format %c [expr {$int % 128}]]$res
        set int [expr {$int >> 7}]
    }
    set res
 }

Examples:
 % base128'encode ""
 0
 % base128'encode hello
 28130883183
 % base128'encode "Tcl & Tk"
 47726922213894763
 % base128'decode 47726922213894763
 Tcl & Tk