#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char lin
ID: 3745852 • Letter: #
Question
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char line[1024];
int len;
int val;
char *p;
if((fgets(line, sizeof(line), stdin)) != NULL) {
p = fgets(line, 1024, stdin); /* read a line from standard input */
len = strlen(line);
strcpy(line, " 65 0x36"); /* give line a new value */
p = &line[3];
}
sscanf(p, "%d", &val);
printf("val=%d%c ",val,val);
p = &line[8];
sscanf(p, "%d", &val);
printf("val=%d%c ", val,val);
I am trying to write a program that reads in a decimal or hexidecimal number and transforms it to the ascii value. I am not sure where to go from here so any help would be appreciated.
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];
int i,choice,len;
printf("Enter your choice : 1. Convert decimal number to ASCII value 2. Convert hexadecimal number to ASCII value Enter your choice :");
scanf("%d",&choice);
switch(choice){
case 1:
printf("Enter a decimal number :");
scanf("%s",c);
len=strlen(c);
for(i=0;i<len;i++){
printf("%d",c[i]);
}
break;
case 2:
printf("Enter a hexadecimal number :");
scanf("%s",c);
int val=convertToDec(c,len);
char str[1000];
toString(str,val);
len=strlen(str);
for(i=0;i<=len-1;i++){
printf("%d",str[i]);
}
break;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.