判断C语言中int 与 unsigned 乘法是否会溢出

在C语言中,int 与 unsigned 乘法被定义为产生w(w为机器字长)位的值。如果乘积超过w位,所产生乘积的高位将被舍弃。

下面这段代码用来判断整数乘法会不会溢出:

/*练习题2.36*/
/*开发环境VC++ 6.0*/
#include

void main(){
 unsigned x = 4294967295;
 unsigned y = 8;
 unsigned mul = x * y;

 int a = 2147483647;
 int b = 8;
 int m = a * b;

 unsigned short d = 65535;
 unsigned short e = 1;

 /*
 printf(“unsigned: %u\n”, mul);
 printf(“0X%0X\n”,mul);
 printf(“signed: %d\n”, m);
 printf(“0X%0X\n”,m);
 */

 printf(“%d\n”,tmulOK(a,b));
 printf(“%d\n”,tmulOK2(a,b));
 printf(“unsigned short: %d\n”,tmulOK2(d,e));
 printf(“%d\n”,tmulOK3(x,y));
}

/*判断两整数相乘是否溢出,不溢出则返回1*/
int tmulOK(int x, int y){
 int p = x * y;
 return !x || p/x == y;
}

/*判断两整数相乘是否溢出,不溢出则返回1*/
int tmulOK2(unsigned short x, unsigned short y){
 int m = x * y;
 
 unsigned short i = ~0;
 int l = i;

 printf(“m = 0X%0X\n”,m);
 printf(“l = 0X%0X\n”,l);
 return (m & ~l) == 0;
}

/*判断两整数相乘是否溢出,不溢出则返回1*/
int tmulOK3(unsigned  x, unsigned  y){
 _int64 m = (_int64)x * y; /*_int64(也可写为__int64)为64位整数。此处的(_int64)强制类型转换相当重要,如果不加此强制类型转换则
x*y就会按照32位乘法进行运算,这样乘积中高

Add a Comment

电子邮件地址不会被公开。 必填项已用*标注