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

前端 未结 3 1598
旧巷少年郎
旧巷少年郎 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:53

    It's because %x has default size of int.
    If you want char, use %hhx
    Or better, you have the macros in <cinttypes>, like PRIx8

    0 讨论(0)
  • 2021-01-12 03:56

    When you pass char value to sprintf() or any other variadic C function it is promoted to int value -1 in this case. Now you print it as unsigned int by "%X" spec, so you get long number with FF. unsigned char on another side promoted to unsigned int so you get 0xFF integer value which is printed as 2 symbols.

    Note: the fact that you specify %X - unsigned int in printf() formatting only affects how printf function treats the value passed to it. Char -> int promotion happens before printf() called and format specifier does not have effect, only type of the value you are passing.

    0 讨论(0)
  • 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 <inttypes.h> for the matching specifiers.

    #include <inttypes.h>
    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);`
    
    0 讨论(0)
提交回复
热议问题