Tcl expressions with hex numbers?
Asked Answered
E

2

9

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?

Epithelium answered 1/2, 2012 at 17:6 Comment(0)
L
12

the format command is what you're after:

format 0x%x [expr {0xa + 0xa}]  ;# ==> 0x14
Ladybug answered 1/2, 2012 at 18:9 Comment(2)
It seems the binary case doesn't work: format %b 0xa fails instead or returning 1010.Epithelium
Tcl's format does not have a "%b" (see the link to the documentation in my answer). You can find Tcl code to return a string of binary digits here. Tcl 8.6 (still in beta) DOES have a "%b" formatter.Ladybug
B
6

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.

Beverlybevers answered 1/2, 2012 at 18:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.