Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tcl expressions with hex numbers?

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?

like image 662
Vahagn Avatar asked Feb 01 '12 17:02

Vahagn


2 Answers

the format command is what you're after:

format 0x%x [expr {0xa + 0xa}]  ;# ==> 0x14
like image 194
glenn jackman Avatar answered Nov 17 '22 02:11

glenn jackman


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.

like image 43
kostix Avatar answered Nov 17 '22 01:11

kostix