int和unsigned int的区别- -

本文详细探讨了int和unsigned int两种数据类型之间的区别,重点分析了它们在移位运算、比较运算上的不同之处,以及这些差异如何影响结果的计算。

int和unsigned int的区别
1移位运算
为int生成的是算术移位指令SAL和SAR
为unsigned int生成的是逻辑移位指令SHL, SHR
对标志位的影响没有深入研究。
对结果的影响:
SHL, SHR都是直接左移,右移,SAL也是,SAL 0x80000000, 1 = 0
但SAR不是简单的移位,对正数是,负数就麻烦一些
SAR 0x80000000, 1 = 0XC0000000
就是对int右移是带符号的除2运算,但和一般的除法运算(IDIV)还不一样
如下
int i = -3;
数学上i/2=-1.5
用idiv做的话就会舍入到-1(向接近0的方向舍入),而用SAR来做会舍入到-2(向接近负无穷的方向舍入)
Intel的文档是这么讲的.
Using the SAR instruction to perform a division operation does not produce the same result as the IDIV instruction. The quotient from the IDIV instruction is rounded toward zero, whereas the “quotient” of the SAR instruction is rounded toward negative infinity. This difference is apparent only for negative numbers. For example, when the IDIV instruction is used to divide -9 by 4, the result is -2 with a remainder of -1. If the SAR instruction is used to shift -9 right by two bits, the result is -3 and the “remainder” is +3; however, the SAR instruction stores only the most significant bit of the remainder (in the CF flag).

所有有 -1 >> 1 == -1

2 比较运算
两个无符号数比较用jbe,...
Jump near if below or equal (CF=1 or ZF=1)
两个有符号数比较用jle...
Jump short if less or equal (ZF=1 or SF<>OF)
一个无符号数与一个有符号数比较用jbe
即把有符号数隐式转换为无符号数

### ### 数据类型定义与表示范围 在C语言中,`unsigned int` `unsigned char` 是两种不同的无符号数据类型,它们的主要区别体现在存储大小数值范围上。`unsigned char` 通常占用1个字节(8位),能够表示的数值范围是0到255。而`unsigned int` 在大多数系统中占用4个字节(32位),可以表示从0到4294967295的数值[^3]。 ### ### 整型提升与符号扩展的影响 当对`unsigned char`进行算术运算或赋值给更大的数据类型(如`int`)时,会发生整型提升。在这种情况下,由于`unsigned char`没有符号位,其最高位被视为数据位,在扩展过程中不会进行符号扩展,而是直接填充高位为零。这种处理方式保证了原始数值在更大范围内保持不变。相比之下,如果使用的是有符号类型的变量(例如`char`),则会根据其最高位(符号位)进行扩展[^2]。 ### 示例代码:展示`unsigned char``unsigned int`之间的差异 ```c #include <stdio.h> int main() { unsigned char uc = 255; unsigned int ui = 255; // 当uc被提升为int时,它的值仍然是255 printf("Size of unsigned char: %zu bytes\n", sizeof(uc)); printf("Value of unsigned char after promotion: %d\n", (int)uc); // ui已经是较大的数据类型 printf("Size of unsigned int: %zu bytes\n", sizeof(ui)); printf("Value of unsigned int: %u\n", ui); return 0; } ``` ### ### 应用场景的选择依据 选择使用`unsigned char`还是`unsigned int`取决于具体的应用需求。对于需要精确控制内存使用的场合,比如处理图像像素或者网络数据流,`unsigned char`更为合适。而在执行大量数学计算时,则更适合使用`unsigned int`来避免频繁的类型转换潜在的溢出问题[^1]。 ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值