Main Content

Converting between Hex and Decimal in Tcl

Archive - Originally posted on "The Horse's Mouth" - 2006-06-28 00:12:16 - Graham Ellis

Tcl is much used in the semiconductor industry, so there's a common requirement to use it to convert values back and forth between hexadecimal (base 16) and decimal (base 10).

Easily done! The format command can be used to convert from decimal to hexadecimal, and the expr command can be used to convert in the opposite direction ... Let's see an example:

set initial 157

# Decimal to hex using format
set inhex [format %x $initial]

# Hex to decimal using expr
set back_in_decimal [expr 0x$inhex]

# checking the results
puts "$initial ... $inhex ... $back_in_decimal"


When I run that, I get ...

157 ... 9d ... 157