How to print 1 byte with printf?

后端 未结 4 639
难免孤独
难免孤独 2020-12-31 08:17

I know that when using %x with printf() we are printing 4 bytes (an int in hexadecimal) from the stack. But I would like to print only

4条回答
  •  心在旅途
    2020-12-31 08:39

    Assumption:You want to print the value of a variable of 1 byte width, i.e., char.

    In case you have a char variable say, char x = 0; and want to print the value, use %hhx format specifier with printf().

    Something like

     printf("%hhx", x);
    

    Otherwise, due to default argument promotion, a statement like

      printf("%x", x);
    

    would also be correct, as printf() will not read the sizeof(unsigned int) from stack, the value of x will be read based on it's type and the it will be promoted to the required type, anyway.

提交回复
热议问题