Home > Back-end >  Looking for nbit adder in c
Looking for nbit adder in c

Time:08-05

I was trying to build 17bit adder, when overflow occurs it should round off should appear just like int32.

eg: In int32 add, If a = 2^31 -1 
int res = a 1
res= -2^31-1

Code I tried, this is not working & is there a better way. Do I need to convert decimal to binary & then perform 17bit operation

int addOvf(int32_t result, int32_t a, int32_t b)
{  
    int max = (-(0x01<<16))
    int min = ((0x01<<16) -1)
    int range_17bit = (0x01<<17);

    if (a >= 0 && b >= 0 && (a > max - b)) {
        printf("...OVERFLOW.........a=
 b=
",a,b);
    }
    else if (a < 0 && b < 0 && (a < min - b)) {
        printf("...UNDERFLOW.........a=
 b=
",a,b);
    }
   
     result = a b;
     if(result<min) {
         while(result<min){ result=result   range_17bit; }
     }
     else if(result>min){
         while(result>max){ result=result - range_17bit; }
     }
     return result;
}

int main() 
{
        int32_t res,x,y;
        x=-65536;
        y=-1;
        res =addOvf(res,x,y);
        printf("Value of x=
 y=
 res=
",x,y,res);
        return 0;
}

CodePudding user response:

You have your constants for max/min int17 reversed and off-by-one. They should be

max_int17 = (1 << 16) - 1 = 65535

and

min_int17 = -(1 << 16) = -65536.

Then I believe that max_int_n m == min_int_n (m-1) and min_int_n - m == max_int_n - (m-1), where n is the bit count and m is some integer in [min_int_n , max_int_n]. So putting that all together the function to treat two int32's as though they are int17's and add them would be like

int32_t add_as_int17(int32_t a, int32_t b) {
    static const int32_t max_int17 = (1 << 16) - 1;
    static const int32_t min_int17 = -(1 << 16);
    auto sum = a   b;
    if (sum < min_int17) {
        auto m = min_int17 - sum;
        return max_int17 - (m - 1);
    } else if (sum > max_int17) {
        auto m = sum - max_int17;
        return min_int17   (m - 1);
    }
    return sum;
}

There is probably some more clever way to do that but I believe the above is correct, assuming I understand what you want.

  •  Tags:  
  • c
  • Related