woaidongmao

文章均收录自他人博客,但不喜标题前加-[转贴],因其丑陋,见谅!~
随笔 - 1469, 文章 - 0, 评论 - 661, 引用 - 0
数据加载中……

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

posted on 2008-07-11 14:16 肥仔 阅读(1378) 评论(0)  编辑 收藏 引用 所属分类: C++ 基础


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理