Version 3 of Switching between Unicode codes and characters

Updated 2011-06-26 11:23:52 by WJG

WJG (26/JUN/11) A while ago Richard Suchenwirth posted the very use proc to convert Unicode screen characters to ascii code values.

#---------------
# convert unicode character to ascii escape sequence
# source: http://wiki.tcl.tk/515
#---------------
proc u2a {s} {
    set res ""
    foreach i [split $s ""] {
        scan $i %c c
        if {$c<128} {append res $i} else {append res [format %04.4X $c]}
    }
    return $res
} ;#RS

But, what if want to convert the other way around, from codes to characters? It seems to me that there are two ways to do the job:

#~~~~~~~~~~~~~~~
# convert unicode to character
# U+3405
#~~~~~~~~~~~~~~~
proc unicode2char { code } {
    eval set str "\\u[string map "U+ {}" $code]"
}

proc uni2char {code} {
    set val [scan $code "U+%x"]
    return [format %c $val]
}