I am trying to convert base 20 to int
. For example if I have "1A"
it needs to be converted to 30
, and so on. I have developed the code but it is giving issues in running. Code is as below in C programming language:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Hello world!\n");
char converted[20] = "1A";
itov(converted);
return 0;
}
void itov(char vigesimalStr[])
{
int length = 0;
for (int i = 0; vigesimalStr[i] != '\0'; i++)
{
length++;
}
int base = 20;
int result = 0;
int power = 1;
int num = 0;
for (int j = length; j >= 0; j--)
{
if (val(vigesimalStr[j]) >= base)
{
printf("Invalid Number");
return -1;
}
num += val(vigesimalStr[j]) * power;
power = power * base;
}
}
int val(char c)
{
if (c >= '0' && c <= '9')
return (int)c - '0';
else
return (int)c - 'A' + 10;
}
I will begin by stating the obvious, there is already a library function that can convert a string containing a number in any base from (I believe) 2 to 36:
printf("%ld\n", strtol("1A", NULL, 20));
// Output: 30
If, however, as part of an exercise or homework assignment the use of this and similar library functions are prohibited, I will not do your homework for you, but I will instead give you a description of the high level algorithm for reading an integer in an arbitrary base, N:
accumulator
variable at zero. i
at 0
. accumulator
by N. str[i]
, and add that to accumulator
(your val
function). i
. str[i]
is '\\0'
, return accumulator
and exit. Otherwise, go to step 3. Two key issues I see in your code:
void itov(char vigesimalStr[])
// ...
return -1;
The itov()
function can't be void
if it returns -1 on error. It also fails to return the correct value on success!
for (int j = length; j >= 0; j--)
When running a sequence backward, you want to start at length - 1
as length
itself is never a valid index as it's the last index plus one.
Below is a rework of your code with the above issues fixed and other lesser issues tidied up:
#include <stdio.h>
#include <stdlib.h>
#define BASE 20
int val(char c)
{
if ('0' <= c && c <= '9')
return c - '0';
return c - 'A' + 10;
}
int itov(char vigesimalStr[])
{
int length = 0;
for (length = 0; vigesimalStr[length] != '\0'; length++)
{
// nothing to see here
}
int power = 1;
int number = 0;
for (int j = length - 1; j >= 0; j--)
{
int digit = val(vigesimalStr[j]);
if (digit >= BASE)
{
fprintf(stderr, "Invalid Number\n");
return -1;
}
number += digit * power;
power *= BASE;
}
return number;
}
int main()
{
char to_convert[20] = "1A";
printf("%d\n", itov(to_convert));
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.