Tcl expressions with hexadecimal numbers?

Function of the Tcl expr supports the arguments, written in hexadecimal notation: operands starting with 0x , are treated as integers, written in hexadecimal form.

However, the return value of expr always in decimal form: expr 0xA + 0xA returns 20 , not 0x14 .

Is there any way to tell expr to return a hexadecimal representation? Is there a Tcl function that converts decimal to hex?

+4
source share
2 answers

format command is what you need:

 format 0x%x [expr {0xa + 0xa}] ;# ==> 0x14 
+8
source

I would like to elaborate on the role of Glenn in order to make things clearer for Vahagn.

expr does not return the result in a single representation, but instead returns a value in some suitable internal format (integer, large integer, floating-point value, etc.). What you see in your testing is just a Tcl interpreter that converts the fact that expr returns to its corresponding text form, using the default conversion to a string, which for integers naturally uses base 10.

This conversion occurs in your case solely because you want to display the value returned by expr , and the display of (any) values โ€‹โ€‹naturally tends to convert them to strings if they are "printed" on to the tkcon window, etc.

Using format , you execute any string representation that you want instead of the standard one. Since format already returns a value that is an internal string, conversion is not performed when printing. A.

+5
source

Source: https://habr.com/ru/post/1394226/


All Articles