|
- /*Date Define*/
- #define SIZE_OF_LARGENUM 3 //宏定义,用于定义LARGENUM可计算的位数SIZE_OF_LARGENUM×32bit
- typedef int UINT32;
- typedef char BOOL;
- typedef struct {
- BOOL fNegative;
- UINT32 u[SIZE_OF_LARGENUM];
- } LARGENUM;
- LARGENUM Num1, Num2;
- /*
- //Compare the Num1 and Num2
- //Note: the compare ignore the signs
- //if Num1 greater than Num2 return TRUE
- //if Num2 greater than Num1 return FALSE
- */
- BOOL
- LargeNumCompare(
- PLARGENUM pNum1,
- PLARGENUM pNum2
- )
- {
- int i;
- for(i=SIZE_OF_LARGENUM-1; i>=0; i--){
- if(pNum1->u.s32.u[i] > pNum2->u.s32.u[i]){
- return TRUE;
- } else if(pNum1->u.s32.u[i] < pNum2->u.s32.u[i]){
- return FALSE;
- }
- }
- return FALSE;
- }
- int main()
- {
- /*Set Num1 of 0x123456789ABCDFE*/
- Num1.fNegtive = FALSE; //FALSE means the Num1 is not negtive number
- Num1.u[0] = 0x9ABCDFEl;
- Num1.u[1] = 0x12345678l;
- /*Set Num1 of 0x987654321FEDCBA*/
- Num2.fNegtive = FALSE; //FALSE means the Num1 is not negtive number
- Num2.u[0] = 1FEDCBAl;
- Num2.u[1] = 0x98765432l;
- if ( LargeNumCompare( &Num1,&Num2 ) ){
- //Num1 is greater than Num2
- //Add the code...
- }
- else{
- //Num2 is greater than Num1
- //Add the code...
- }
- }
复制代码
上面的代码就可以了,只不过没有比较由符号的情况,要考虑由符号的情况,在原来函数的基础上考虑符号即可,原函数相当于只考虑了符号相同且均为正数,还剩下符号相反,符号相同为负数,原理类似。
只需考虑好数字的拼接就可以了,类似的可以做加减乘除运算;
上面的函数基本计算单位为32位,如果数字位数更大的话,比如两个128位数比较,只需修改SIZE_OF_LARGENUM宏即可,128/32= 4;
其实这就是个迭代运算。
有用的话,请加分,呵呵 |
|