int类型的二进制内存表示、最大最小值计算
计算Int最大最小值
通常我们会使用CRT提供给我们的一个头文件<limits.h>中预定义宏INT_MAX, INT_MIN, UINT_MAX来定义int的最大最小值
下边给出由计算得出这些值的方法,其他数据类型同理
下边给出由计算得出这些值的方法,其他数据类型同理
unsigned int GetUnsignedIntMax()
{
return ~ 0 ;
}
signed int GetSignedIntMax()
{
return (static_cast < unsigned int > ( ~ 0 )) >> 1 ;
}
signed int GetSignedIntMin()
{
signed int i = - 1 ;
if (i & 1 )
return - ( (static_cast < unsigned int > ( ~ 0 )) >> 1 ) - 1 ; // 一般都是这个
else
return - ( (static_cast < unsigned int > ( ~ 0 )) >> 1 );
} 稍微解释一下,前两个没有什么好说的,最后一个要考虑是two complement还是one complement
如果是前者,有这样一个计算公式,~X + 1= -X,即一个数取反加一表示这个数所对应的负数
如果是前者,有这样一个计算公式,~X + 1= -X,即一个数取反加一表示这个数所对应的负数
The two's complement encoding can represent the following range of numbers
Zero representation is
The maximum positive number is
The minimum, non-zero, positive number (smallest absolute value) is
The minimum negative number is
The maximum negative number (smallest absolute value) is
0. int在内存中占4*8 = 32bit,对于signed类型,最高位是符号位。
1. 一般计算机都是two complement,所以-1的二进制内存表示就是全是
。
2. 在two complement的计算机上,~X + 1= -X,即一个数取反加一表示这个数所对应的负数






浙公网安备 33010602011771号