I am writing a C program that reads in decimal and hexidecimal values and displa
ID: 3746746 • Letter: I
Question
I am writing a C program that reads in decimal and hexidecimal values and displays the ascii value. I am having trouble differientiating between the two inputs. I am using isdigit and isxdigit but my input for the hexidecimal input is in the format 0x... to show that it is a hex input. How can I adjust my code to accept these values as hex and differentiate between hex and dec? I have included my code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include<ctype.h>
int main() {
char line[1024];
for(int i=0;i<1024;i++){
line[i]='';
}
int len;
int val;
char *p;
while((p = fgets(line, sizeof(line), stdin)) != NULL) { /* read a line from standard input */
len = strlen(line)-2;
for(int i = 0; i < len; i++) {
p = &line[i];
if(isxdigit(line[i])) {
sscanf(p, "%x", &val);
printf("%c", val);
}
else if(isdigit(line[i])){
sscanf(p, "%d", &val);
printf("%c", val);
}
/*else if(isalpha(line[i])) {
printf("Error ");
}*/
}
}
printf(" ");
return 0;
Explanation / Answer
#include<stdio.h>
int convertToDec(char c[],int len){
int i,b=1,val=0;
for(i=len-1;i>=0;i--){
if(c[i]>='0'&&c[i]<='9'){
val=val+(c[i]-48)*b;
b=b*16;
} else if (c[i]>='A'&&c[i]<='F'){
val=val+(c[i]-55)*b;
b=b*16;
}
}
return val;
}
void toString(char str[],int val){
int i=0;
while(val!=0){
str[i]=val%10+'0';
val=val/10;
i++;
}
str[i]='';
strrev(str);
}
int main(){
char c[1000],hex[1000];
int i,choice,len,flag=1,val,j=0,l;
printf("Enter a value :");
scanf("%s",c);
len=strlen(c);
for(i=0;i<len;i++)
{
if(flag==0){
hex[j]=c[i];
j++;
}
if(c[i]=='x'||c[i]=='X')
{
flag=0;
}
}
switch(flag){
case 0:
l=strlen(hex);
val=convertToDec(hex,l);
char str[1000];
toString(str,val);
len=strlen(str);
for(i=0;i<=len-1;i++){
printf("%d",str[i]);
}
break;
case 1:
for(i=0;i<len;i++){
printf("%d",c[i]);
}
break;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.