%02x和%2x区别

%02x  (x代表以十六进制形式输出,02代表不足两位,前面补0输出,如果超过两位,则以实际输出)

例:

#include <stdio.h>
#include <stdint.h>
#include <string.h>

typedef struct xxx{

    uint8_t a;
    uint8_t b;
    uint32_t c;

} stu;



int main()
{

    int i;
    stu s;
    memset(&s, 0, sizeof(s));
    s.a = 0x01;
    s.b = 0x02;
    s.c = 0x1C080206;

    unsigned char *p = (unsigned char *)&s;
    
    for (i = 0; i < sizeof(s); i++) {
        printf("p[%d] = %02x\n", i, p[i]);        
    }    

    return 0;
}

运行结果:

p[0] = 01
p[1] = 02
p[2] = 00
p[3] = 00
p[4] = 06
p[5] = 02
p[6] = 08
p[7] = 1c

PS: 不考虑大小端和内存对齐。

%2x (数据不足两位,实际输出;注意:不会额外补0,如果超过两位,则以实际输出)

例:

#include <stdio.h>
#include <stdint.h>
#include <string.h>

typedef struct xxx{

    uint8_t a;
    uint8_t b;
    uint32_t c;

} stu;



int main()
{

    int i;
    stu s;
    memset(&s, 0, sizeof(s));
    s.a = 0x01;
    s.b = 0x02;
    s.c = 0x1C080206;

    unsigned char *p = (unsigned char *)&s;
    
    for (i = 0; i < sizeof(s); i++) {
        printf("p[%d] = %2x\n", i, p[i]);        
    }    

    return 0;
}

运行结果:

p[0] = 1
p[1] = 2
p[2] = 0
p[3] = 0
p[4] = 6
p[5] = 2
p[6] = 8
p[7] = 1c

猜你喜欢

转载自www.cnblogs.com/yongdaimi/p/9075581.html