How to print 1 byte with printf?

后端 未结 4 616
难免孤独
难免孤独 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:33

    You can use the following solution to print one byte with printf:

    unsigned char c = 255;
    printf("Unsigned char: %hhu\n", c);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-31 08:51

    You need to be careful how you do this to avoid any undefined behaviour.

    The C standard allows you to cast the int to an unsigned char then print the byte you want using pointer arithmetic:

    int main()
    {
        int foo = 2;
        unsigned char* p = (unsigned char*)&foo;
        printf("%x", p[0]); // outputs the first byte of `foo`
        printf("%x", p[1]); // outputs the second byte of `foo`
    }
    

    Note that p[0] and p[1] are converted to the wider type (the int), prior to displaying the output.

    0 讨论(0)
  • 2020-12-31 08:51

    If you want to print a single byte that is present in a larger value type, you can mask and/or shift out the required value (e.g. int x = 0x12345678; x & 0x00FF0000 >> 16). Or just retrieve the required byte by casting the needed byte location using a (unsigned) char pointer and using an offset.

    0 讨论(0)
提交回复
热议问题