printf与[unsigned] char

在订阅的某邮件列表里看见这样一个问题:


Hi, having coding in C for 3 years but I'm still not clear with this one.

Consider this code.
...
char *p;
unsigned int i = 0xcccccccc;
unsigned int j;
p = (char *) &i;
printf("%.2x %.2x %.2x %.2x\n", *p, p[1], p[2], p[3]);
memcpy(&j, p, sizeof(unsigned int));
printf("%x\n", j);
...
Output:
ffffffcc ffffffcc ffffffcc ffffffcc
0xcccccccc

My questions are:
1. Why it prints "ffffffcc ffffffcc ffffffcc ffffffcc"? (if p is
unsigned char* then it will print correctly "cc cc cc cc")
2. Why pointer to char p copied to j correctly, why not every member

in p overflow? since it is a signed char.


问题2我想不用多说了,我觉着没什么问题。

问题1是个不常用的printf特性,自己实验了一下。

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
        char a = 0xcc;
        unsigned char b = 0xcc;
        printf("%.2x\n", a);
        printf("%.2x\n", b);

        char *p = &a;
        unsigned char *q = &a;
        printf("%.2x\n", *p);
        printf("%.2x\n", *q);

        p = &b;
        q = &b;
        printf("%.2x\n", *p);
        printf("%.2x\n", *q);

        exit(0);
}

结果如下:

gcc printf.c && ./a.out
ffffff8c
cc
ffffff8c
8c
ffffffcc
cc



发现结论如下:

当以%.2x格式打印


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值