Reputation: 71
I'm brand new to C and i'm working on a method that converts an ascii to an integer. So bascially if i have ABCD (base 16) ill get 43981 (base 10).. Just a short walk through of what i have. I take one digit at i time from the string then that number needs to be translated so i call my chartoint method. Then i think i need to * the pervious result by the base before i add the new number. I am also confused on the printf method. Here is my method so far.
void ascii2int(char *ascii, int base){
int totalstring = 0;
if(2<= base && base <= 16){
for (int i = 0; i < strlen(ascii); i++) {
// Extract a character
char c = ascii[i];
// Run the character through char2int
int digit = char2int(c);
totalstring= digit * base;
printf("%d/n",totalstring);
}
}
}
char2int
int char2int(char digit){
int converted = 0;
if(digit >= '0' && digit <= '9'){
converted = digit - '0';
}
else if( digit >= 'A' && digit <= 'F'){
converted = digit - 'A' + 10;
}
else{
converted = -1;}
return converted;
}
Upvotes: 0
Views: 964
Reputation: 71
Solution :
void ascii2int(char *ascii, int base){
//int digit = 0;
int totalstring = 0;
if(2<= base && base <= 16){
for (int i = 0; i < strlen(ascii); i++) {
// Extract a character
char c = ascii[i];
// Run the character through char2int
int digit = char2int(c);
totalstring = totalstring * base + digit;
}
printf("%d", totalstring);
}
}
Upvotes: 0
Reputation: 30136
Assuming that function char2int
is implemented correctly...
Change this:
totalstring = digit * base;
To this:
totalstring *= base; // totalstring = totalstring * base
totalstring += digit; // totalstring = totalstring + digit
Or to this:
totalstring = totalstring * base + digit;
In addition, call printf
outside the for
loop (and change that /n
to \n
).
Upvotes: 3