歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

判斷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 name="code">/*判斷兩整數相乘是否溢出,不溢出則返回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;
}

Copyright © Linux教程網 All Rights Reserved