printf the last Byte of a hex value in C

前端 未结 2 1599
梦如初夏
梦如初夏 2021-01-22 00:15

I have a simple question. The code is really short so I just post it here

#include 
int main(int argc, const char * argv[])
{

    long int p;

           


        
相关标签:
2条回答
  • 2021-01-22 01:05

    To print the least-significant byte of *q in hex you could use:

    printf("%02x", *q & 0xFF);
    

    This of course assumes that q can be dereferenced.

    0 讨论(0)
  • 2021-01-22 01:08

    First convert to unsigned:

    unsigned char q = *(unsigned char *)(p);
    printf("%02X", q);
    

    (Otherwise, if your char is signed, the variadic default promotion converts the value to int, and the result may be negative.)

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