c - unsigned short int 与 unsigned int 有何不同

标签 c unsigned short

#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 short int在数据保存场景中与unsigned int有何不同。即 x=65526 where as z=-10000000 why x is not equal -10 where as z can hold any data 由于 short 是 2 字节所以 twos complement -10 is 65526但为什么在 z

case 中不一样

最佳答案

unsigned short int x=-10;发生,x , 无符号, 得到 65526 的模数或“包装”值(OP sizeof(short) 为 2)。类似于 x = power(256,sizeof(unsigned short)) - 10 .

x被打印,它被传递给printf()作为int (变量提升)。 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通常是处理器最佳使用的 native 大小 - 通常最快。

作为unsigned short int在某些实现中,小于 unsigned int .它是大型阵列节省空间的首选。

关于c - unsigned short int 与 unsigned int 有何不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19335839/

相关文章:

c - 声明 "int t[0];"的作用是什么?

c++ - 使用无符号值时保护 Cin

java - 将有符号字节转换为无符号半字节

c++ - 无符号长整型和位移位

java读取并写入\u05DC为 '?'

floating-point - 是否可以使用带符号的短 "2 bytes"而不是浮点 "4 bytes"导出 glTF 模型的顶点、UV 和法线?

c++ - execve() 的 envp arg 中的 LD_LIBRARY_PATH 被删除,即使调用 setuid parent prog 放弃了它的特权

c - C中结构中的段错误

c++ - unsigned short int 和 unsigned int 或 unsigned short 之间有什么区别?

c - 为什么连续声明的指针变量是按照地址递减的顺序存储在内存中的?