2013-10-12 22 views
1
#include<stdio.h> 
int main() 
{ 
    unsigned short int x=-10; 
    short int y=-10; 
    unsigned int z=-10000000; 
    int m=-10000000; 

    printf("x=%d y=%d z=%d m=%d",x,y,z,m); 
    return 0; 
} 

输出不同= x=65526 y=-10 z=-10000000 m=-10000000如何无符号短整数从unsigned int的

我的查询是如何在unsigned short int保持数据的场景从unsigned int不同。即x=65526 where as z=-10000000 why x is not equal -10 where as z can hold any data作为短是2字节,以便twos complement -10 is 65526但为什么不能在的z

+1

http://stackoverflow.com/questions/3812022/what-is-a-difference-between-unsigned-int-and-signed-int-in-c – Rulisp

+0

'sizeof(unsigned short int)'和'sizeof (unsigned int)' –

回答

4

case相同当unsigned short int x=-10;发生时,x,作为无符号时,获取模或65526“包装”值(OP的sizeof(短)为2)。像x = power(256,sizeof(unsigned short)) - 10

当打印x时,作为int(可变参数促销)传递给printf()。 OP的sizeof(int)是4,所以65526适合于int。然后printf()看到一个%d并打印“65526”。

z有一个类似的故事,但sizeof(z)是4.并获得初始化z = power(256,sizeof(unsigned)) - 10

您的printf()正在使用%d说明符unsigned。 OP应该使用%u

printf("x=%u y=%d z=%u m=%d",x,y,z,m); 

unsigned short int保证在至少范围为0〜覆盖到65535

unsigned int保证在至少unsigned short int的范围覆盖。它可能覆盖面更广。

unsigned int通常是处理器最佳使用的本机尺寸 - 通常最快。

由于unsigned short int在一些实施方式中小于unsigned int。大型阵列节省空间是首选。

相关问题