I was going through one of the example codes of esp-idf and I found out that they were using the following syntax to print hex number.
ESP_LOGE(TAG, "mbedtls_ssl_handshake returned -0x%x", -ret);
The ESP_LOGE()
syntax just prints the output to the console through UART. I am not understanding what is the use of "-" in it. Can anyone help me why they have used "-" in it? The code which I was referring to is here. When I tried a simple example to print the same hex using CI was getting different output when I used -ret
and when I replaced it with ret
.
%x
will print hex representation of the unsigned number.
example:
int x = -0x45;
printf("%x\n", x);
https://godbolt.org/z/j3r3nv1s1
It will print (assuming two's complement 32 bits integers) ffffffbb
which is not you want to see if you intended to print a negative hex number. You need to convert it to a positive number and simply add -
to the format string. REMEMBER in two complement's system it will not work for INT_MIN number and it will invoke an Undefined Behaviour.
int x = -0x45;
printf("-%x\n", -x); //you can also use abs(x)
It will output -45. https://godbolt.org/z/ePbdrcqb5
You may add 0x
as well to show that number is in hex format.
printf("-0x%x\n", -x);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.