-1
**Allocation and Storage part of C programming **

在尝试通过不同的数字系统打印负数时,我产生了一些疑问。在打印负数时,我得到不同的输出值。但我不清楚。如果有人帮助我,将不胜感激。

 #include<stdio.h>
    int main( )
    {
       char a = -5;
       unsigned char b = -5;
       int c = -5;
       unsigned int d = -5;

      //try to print as using "%d" format specifier to display decimal value
      printf("%d %d",a,b);
      printf("%d %d",c,d);

      //try to print as using "%o" format specifier to display octal value
      printf("%o %o",a,b);
      printf("%o %o",c,d);

      //try to print as using "%x" format specifier to display hexa-decimal value
      printf("%x %x",a,b);
      printf("%x %x",c,d);

      return 0;
}

输出:-

displaying decimal value 
a = -5 b = 251
c = -5 d = -5

displaying octal value
a = 37777777773 b = 373
c = 37777777773 d = 37777777773

displaying Hexa-decimal value
a = fffffffb  b = fb
c = fffffffb  d = fffffffb

现在,进入正题。我不知道为什么 unsigned char 只占用 8 位(1 字节)而其他分配给 32 位(4 字节)。

4

1 回答 1

1

当一个char值被传递给 时printf,它被提升为intprintf正在打印此int值。

char值为 -5 并提升为int时,int值为 -5。对于 32 位二进制补码int,-5 用位 fffffffb 16表示。因此,当您要求printf使用 进行格式化时%x,您可以“fffffffb”。(从技术上讲,%xis for anunsigned int和传递 anint不匹配,但大多数 C 实现都会接受它。)8 位char被提升为 32 位int,这就是您看到 32 位结果的原因。

您可以通过使用or代替or来判断printf它接收到的值源自字符值,并且它可能会相应地进行调整。(同样,and说明符用于值,传递 an不匹配,但它可能有效。)一个迂腐正确的解决方案是在传递有符号的 a 或转换时使用。%hho%hhx%o%xoxunsigned intint(unsigned int) (unsigned char) xchar x%o%x

于 2020-06-08T09:58:08.543 回答