Re: Please comment on my program
- From: jaysome <jaysome@xxxxxxxxxxx>
- Date: Mon, 25 Sep 2006 22:37:26 -0700
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
.
- References:
- Please comment on my program
- From: Registered User
- Re: Please comment on my program
- From: CBFalconer
- Please comment on my program
- Prev by Date: Re: C Strings not returning from a function
- Next by Date: Re: learn me c
- Previous by thread: Re: Please comment on my program
- Next by thread: Re: Please comment on my program
- Index(es):
Relevant Pages
|
|