Chinaunix

标题: 新手请教一个printf的问题 [打印本页]

作者: ck_lai    时间: 2008-01-25 12:01
标题: 新手请教一个printf的问题
代码如下:

int main()
{
    char a = 0x7f;
    char b = 0xf7;

    printf("a=%02x,b=%02x\n")
    return 0;
}

结果:
a=7f, b=fffffff7

如果定义a,b都为unsigned char类型,则:
a=7f, b=f7

    这个问题应该和正负数有关吧?但是我不明白是什么原因造成的,
请各位指教,谢谢
作者: flw2    时间: 2008-01-25 12:38
参数传递的时候会被符号扩展
作者: xi2008wang    时间: 2008-01-25 12:39
它们都用8位表示
char 有符号 整数范围为-128到127( 0x80__0x7F),  f7超过范围成为负数
unsigned char 无符号 整数范围为0到255( 0__0xFF ) f7在范围内
作者: FinalBSD    时间: 2008-01-25 12:57
16进制     2 进制           10进制
--------------------------------------------
0x7f          1111111              127
0xf7          11110111            247
char 有符号 整数范围为-128到127
Variables of type char are generally used to hold values defined by the ASCII character set. Values outside that range may be handled differently by different compilers.

[ 本帖最后由 FinalBSD 于 2008-1-25 13:05 编辑 ]
作者: ck_lai    时间: 2008-01-25 14:12
我查了一下man,里面对于%x的描述提及:

o,u,x,X
              The unsigned int argument is converted to  unsigned  octal  (o),
              unsigned  decimal  (u),  or unsigned hexadecimal (x and X) nota-
              tion.

    也就是说本身x的类型就应该是unsigned的,代码中赋予signed的参数,超越
x的范围,所以对于不同的编译器,就出现不同的结果。
    Is it right?




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2