Re: Please comment on my program



On Mon, 25 Sep 2006 10:42:47 -0400, CBFalconer <cbfalconer@xxxxxxxxx>
wrote:

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 <stdio.h>

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.

While it's important to understand that the C Standard does not
guarantee that the character set used to encode 'A'..'Z' or 'a'..'z'
is not contiguous, it's also important to realize that source code
distributed with a particular character encoding is inherently
non-portable. ZIP files containing source code encoded with the ASCII
character encoding are inherently non-portable. True pedantics would
note such a caveat.

Best regards
--
jay
.



Relevant Pages

  • Re: porting vs migrating
    ... I copied the source code file from my IBM mainframe to my Windows box. ... I also compiled it with gcc and got an error: ... I suspect there is a character encoding issue and I ...
    (comp.lang.c)
  • Re: porting vs migrating
    ... I copied the source code file from my IBM mainframe to my Windows box. ... I also compiled it with gcc and got an error: ... I suspect there is a character encoding issue and I ...
    (comp.lang.c)