Version 19 of hexadecimal conversions

Updated 2002-06-11 20:36:27

[...]

[... atoms ...]

[... other pages ...]

    % set hex 3A
    3A
    % scan $hex %x decimal
    1
    % set decimal
    58

Decimal to hex:

 format %4.4X $decimalNumber

Notice that the ".4" part gives leading zeroes, and does not have to do with the fractional (right-of-the-point) part of the number.

Character to hex:

 format %4.4X [scan $c %c]

Notice that "[scan $c %c]" only does what one wants with newer Tcl's, those since version 8.3.0+.


mfi: Can someone suggest a pure Tcl replacement for xxd UNIX command (creates a hex dump of a given string)?

RS: Sure enough:

 proc string2hex {string} {
    set where 0
    set res {}
    while {$where<[string length $string]} {
        set str [string range $string $where [expr $where+15]]
        if {![binary scan $str H* t] || $t==""} break
        regsub -all (....) $t {\1 } t4
        regsub -all (..) $t {\1 } t2
        set asc ""
        foreach i $t2 {
            scan $i %2x c
            append asc [expr {$c>=32 && $c<=127? [format %c $c]: "."}]
        }
        lappend res [format "%7.7x: %-42s %s" $where $t4  $asc]
        incr where 16
    }
    join $res \n
 }

See also Dump a file in hex and ASCII

[LH}: Here's something similar, but speeds things up by using external storage for a character map that is generated one time:

proc xxd2 {charMapname convertString} {

    upvar $charMapname mycharMap

    #generate a character map for displaying hex equiv of chars [0..127]
    if { 0 == [string length $mycharMap] } {
        # init charmap
        for {set i 0 } { $i < 127 } { incr i } { 
            append mycharMap "[format " \\%s {%s }" [format "%03o" $i]  [format "%02x" $i]]"
        }
    }

    string map $mycharMap $convertString

}

#example:

set hexcharMap "" ;# global variable xxd2 hexcharMap "abcdz"


Arts and crafts of Tcl-Tk programming