The Tcl expr
function supports arguments written in hex notation: operands which begin with 0x
are treated as integers written in hex form.
However the return value of expr
is always in decimal form: expr 0xA + 0xA
returns 20
, not 0x14
.
Is there a way to tell expr
to return the hex representation?
Is there a Tcl function which converts decimal representation to hex?
the format
command is what you're after:
format 0x%x [expr {0xa + 0xa}] ;# ==> 0x14
I'd like to elaborate on the glenn's post to make things more clear for Vahagn.
expr
does not return its result in one representation or another, instead, it returns a value in some suitable internal format (an integer, a big integer, a floating point value etc). What you see doing your testing is just Tcl interpreter converting what expr
returned to an appropriate textual form using a default conversion to a string which, for integers, naturally uses base 10.
This conversion takes place in your case solely because you wanted to display the value returned by expr
, and displaying of (any) values naturally tends to convert them to strings if they are "printed"—to a terminal, to a tkcon's window etc.
By using format
you enforce whatever string representation you want instead of the default one. Since format
already returns a value which is a string internally, no conversion takes place when it's printed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With