Search code examples
formathextclsigned

TCL: convert negative integer to hexadecimal?


I want to convert signed integer to 32-bit hexadecimal. The following works fine for positive integer:

format %.8x $the_decimal_value

But for negative integer, I got 64-bit hexadecimal. For example, 99 is converted to 00000063, but -81 is converted to ffffffffffffffaf.

Anyone know how to get 32-bit hexadecimal from a negative integer?


Solution

  • % set num -81
    % format 0x%.8x [expr {$num & 0xFFFFFFFF}]
    0xffffffaf
    

    The only hint in the docs I can find is this.