How to print 1 byte with printf?

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

提交回复
热议问题