C - Printing negative int values as hex produces too many characters

前端 未结 3 1632
旧巷少年郎
旧巷少年郎 2021-01-12 03:41

Compile using gcc 4.1.2 on CentOS-5 64 bit.

Printing an integer as a two-character hex string:

#include 
#include 

         


        
3条回答
  •  感情败类
    2021-01-12 03:58

    A int8_t will go through the usual integer promotions as a parameter to a variadic function like printf(). This typically means the int8_t is converted to int.

    Yet "%X" is meant for unsigned arguments. So covert to some unsigned type first and use a matching format specifier:

    For uint8_t, use PRIX8. With exact width types, include for the matching specifiers.

    #include 
    printf(" int negative var is <%02" PRIX8 ">\n", iNegVar);`
    

    With int8_t iNegVar = -1;, convert to some unsigned type before printing in hex

    printf(" int negative var is <%02" PRIX8 ">\n", (uint8_t) iNegVar);`
    

提交回复
热议问题