446,406 Members | 982 Online
Need help? Post your question and get tips & solutions from a community of 446,406 IT Pros & Developers. It's quick & easy.

# Please comment on my program

 P: n/a I'm a newbie and have attempted to create a program to convert a string containing the representation of a number in a specified base to a decimal integer. Here's the code: #include unsigned todecimal( char *s, int base) { unsigned num = 0, mul; int len=0; while (*++s != '\0') ++len; --s; for (mul=1; len>=0; --len, mul*=base, --s) { if (*s >= '0' && *s <= '9') num+= (*s-'0')*mul; else if (*s>='A'&& *s<='Z') num+= (*s-'A'+10)*mul; else if (*s>='a' && *s<='z') num+=(*s-'a'+10)*mul; } return num; } int main() { char s[33]; int base; printf("Enter the number and its base: "); scanf("%s%d",s, &base); printf("Decimal value = %u\n", todecimal(s, base) ); return 0; } Sep 25 '06 #1
5 Replies

 P: n/a Registered User wrote: > I'm a newbie and have attempted to create a program to convert a string containing the representation of a number in a specified base to a decimal integer. Here's the code: #include unsigned todecimal( char *s, int base) { unsigned num = 0, mul; int len=0; while (*++s != '\0') ++len; --s; for (mul=1; len>=0; --len, mul*=base, --s) { if (*s >= '0' && *s <= '9') num+= (*s-'0')*mul; else if (*s>='A'&& *s<='Z') num+= (*s-'A'+10)*mul; else if (*s>='a' && *s<='z') num+=(*s-'a'+10)*mul; } return num; } int main() { char s[33]; int base; printf("Enter the number and its base: "); scanf("%s%d",s, &base); printf("Decimal value = %u\n", todecimal(s, base) ); return 0; } Shows promise, but here are some things to consider: There is no guarantee that the letters 'A'..'Z' are contiguous. Same for 'a'..'z'. See EBCDIC encoding for one example. Nothing stops your conversion if an input 'digit' is beyond the size allowed by base. Nothing detects overflow. -- Some informative links: Sep 25 '06 #2