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,即一个数取反加一表示这个数所对应的负数

 

The two's complement encoding can represent the following range of numbers

Zero representation is

0 : 0,0,\dots,0

The maximum positive number is

2^{m-1} - 2^{-n} : 0,1,1,1,\dots,1,1

The minimum, non-zero, positive number (smallest absolute value) is

2^{-n} : 0,0,0,\dots,0,0,1

The minimum negative number is

-2^{m-1} : 1,0,0,0,\dots,0,0

The maximum negative number (smallest absolute value) is

-2^{-n} : 1,1,1,\dots,1,1
总结几点:

0. int在内存中占4*8 = 32bit,对于signed类型,最高位是符号位。

1. 一般计算机都是two complement,所以-1的二进制内存表示就是全是-2^{-n} : 1,1,1,\dots,1,1

2. 在two complement的计算机上,~X + 1= -X,即一个数取反加一表示这个数所对应的负数 

posted @ 2011-03-02 14:34  能巴  阅读(3226)  评论(0)    收藏  举报