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

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

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

/*练习题2.36*/
/*开发环境VC++ 6.0*/
#include<stdio.h>

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;
}
<PRE class=cpp>/*判断两整数相乘是否溢出,不溢出则返回1*/
int tmulOK3(unsigned  x, unsigned  y){
 _int64 m = (_int64)x * y; /*_int64(也可写为__int64)为64位整数。此处的(_int64)强制类型转换相当重要,如果不加此强制类型转换则
x*y就会按照32位乘法进行运算,这样乘积中高出的32位的更高位将被舍弃。*/
&nbsp;      printf("\ntmulOK3()\n");
 printf("m =  0X%I64d\n",m);
 
 return m == (unsigned)m;
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/46f8a817762e700c7b36269132cf7503.html