Adding Base-n's through strings (between base-2 and base-36)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gdlx
    New Member
    • Feb 2015
    • 1

    #1

    Adding Base-n's through strings (between base-2 and base-36)

    I just wanted to add strings in any base form (example 1101+100 = 10001 in base-2 but it could be added using any base-form like in base-3 to base-36) and I'm having a big trouble with my code because it gave me incorrect results.

    addition(char st[], char st2[], int base){
    int i, j, carry = 0, ans, len, o=0, z=1, l=0;
    char final[50];

    if(strlen(st)>= strlen(st2))
    len = strlen(st);
    else
    len = strlen(st2);

    for(i=len; i>=0; i--){
    if(isdigit(st[i])&&isdigit(st 2[j])){ //if both addends are digits
    ans = (st[i] - '0') + (st2[i] - '0') + carry;
    }
    else if(isdigit(st[i])&&isalpha(st 2[j])){ //if first addend is a digit and second addend is an alphabet
    ans = (st[i] - '0') + (st2[j] - 'A'+10) + carry;
    }
    else if(isalpha(st[i])&&isdigit(st 2[j])){ //if first addend is an alphabet and second addend is a digit
    ans = (st[i] - 'A'+10) + (st2[j] - '0') + carry;
    }
    else if(isalpha(st[i])&&isalpha(st 2[j])){ //if both addends are alphabet
    ans = (st[i] - 'A'+10) + (st2[j] - 'A'+10) + carry;
    }

    if(ans > base){
    ans = ans - base;
    carry = ans - base;
    }
    else if(ans == base){
    ans = ans - base;
    carry = 1;
    }

    if(ans >= 0 && ans <= 9)
    final[i] = ans + 49;
    else if(ans >= 65 && ans <= 90)
    final[i] = ans + 65;

    printf("%c", final[i]);
    }
    }

    I really need help about this code. Thanks :-)
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    I would write functions that convert the string to a base 10 number. Add the numbers for each string. Then call a function to convert the base 10 number to a string in the correct base:
    Code:
    char str1[6] = "11101";
    char str2[7] = "000111";
    char str3[10];
    
    int X = ConvertToInteger(str1, 2);
    int Y = ConvertToInteger(str2, 2);
    
    int Sum = X + Y;
    
    ConvertToString(Sum,str3,2);
    This approach will break your logic into chunks as opposed to a "strem of consciousness" if-else-if code.
    Last edited by weaknessforcats; Feb 27 '15, 05:11 PM. Reason: added a base parameter

    Comment

    Working...