R
Raj
Following is a code to print integer equivalent of a hexadecimal
number. If the entered number starts with a 0x or a 0X, calculation is
done after skipping these two characters. Now, this code works fine
except when i enter 0 as the 1st element & then follow it up with a
non 'x' or non 'X' character.
For e.g. When i enter 09, i get output 0... not only this, if i start
my input with a 0, then output always comes out to be 0. Otherwise the
code works fine. If anybody can help... thanx!
Code:
#include<stdio.h>
int main(void)
{
int n=0,i=0,c;
clrscr();
printf("Enter hexadecimal string\n");
while((c=getchar())!=EOF){
if(c=='0'){
if(i==0)
if(((c=getchar())=='x')||((c=getchar())=='X'))
continue;
}
i++;
if(c>=48&&c<=57)
n=16*n+(c-48);
else if(c>=65&&c<=70)
n=16*n+(c-65)+10;
else if(c>=97&&c<=102)
n=16*n+(c-97)+10;
}
printf("Corresponding integer value is: %d",n);
getch();
return 0;
}
number. If the entered number starts with a 0x or a 0X, calculation is
done after skipping these two characters. Now, this code works fine
except when i enter 0 as the 1st element & then follow it up with a
non 'x' or non 'X' character.
For e.g. When i enter 09, i get output 0... not only this, if i start
my input with a 0, then output always comes out to be 0. Otherwise the
code works fine. If anybody can help... thanx!
Code:
#include<stdio.h>
int main(void)
{
int n=0,i=0,c;
clrscr();
printf("Enter hexadecimal string\n");
while((c=getchar())!=EOF){
if(c=='0'){
if(i==0)
if(((c=getchar())=='x')||((c=getchar())=='X'))
continue;
}
i++;
if(c>=48&&c<=57)
n=16*n+(c-48);
else if(c>=65&&c<=70)
n=16*n+(c-65)+10;
else if(c>=97&&c<=102)
n=16*n+(c-97)+10;
}
printf("Corresponding integer value is: %d",n);
getch();
return 0;
}