简体   繁体   English

将基数20转换为int

[英]Converting base 20 to int

I am trying to convert base 20 to int . 我试图将基数20转换为int For example if I have "1A" it needs to be converted to 30 , and so on. 例如,如果我有"1A"则需要将其转换为30 ,依此类推。 I have developed the code but it is giving issues in running. 我已经开发了代码,但是在运行中却出现了问题。 Code is as below in C programming language: 代码如下使用C编程语言:

#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: 首先,我要说明一个明显的问题,已经有一个库函数可以将包含任何基数的字符串从(我相信)2转换为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: 但是,如果作为练习或家庭作业的一部分,禁止使用此函数和类似的库函数,则我不会为您做家庭作业,而是向您介绍在其中读取整数的高级算法。任意基数N:

  1. Initialize an accumulator variable at zero. accumulator变量初始化为零。
  2. Initialize a count variable i at 0 . 将计数变量i初始化为0
  3. Multiply accumulator by N. accumulator乘以N。
  4. Get the numeric value of the base-N digit currently in str[i] , and add that to accumulator (your val function). 获取str[i]当前以N为底的数字的数值,并将其添加到accumulator (您的val函数)。
  5. Increment i . 递增i
  6. If str[i] is '\\0' , return accumulator and exit. 如果str[i]'\\0' ,则返回accumulator并退出。 Otherwise, go to step 3. 否则,请转到步骤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. 如果错误返回-1,则itov()函数不能为void 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. 向后运行序列时,您要从length - 1开始length - 1因为length本身永远不是有效的索引,因为它是最后一个索引加一个。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM