【问题标题】:converting ascii to an interger (C)将 ascii 转换为整数 (C)
【发布时间】:2014-09-06 21:22:47
【问题描述】:

我是 C 的新手,我正在研究一种将 ascii 转换为整数的方法。因此,基本上,如果我有 ABCD(以 16 为基数),我将得到 43981(以 10 为基数).. 只需几步了解我所拥有的。我每次从字符串中取一个数字,然后需要翻译那个数字,所以我调用我的 chartoint 方法。然后我认为在添加新数字之前,我需要 * 基数的先前结果。我也对 printf 方法感到困惑。到目前为止,这是我的方法。

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

【问题讨论】:

    标签: c loops for-loop ascii


    【解决方案1】:

    假设函数char2int被正确实现...

    改变这个:

    totalstring = digit * base;
    

    到这里:

    totalstring *= base;  // totalstring = totalstring * base
    totalstring += digit; // totalstring = totalstring + digit
    

    或者到这个:

    totalstring = totalstring * base + digit;
    

    此外,在for 循环之外调用printf 外部(并将/n 更改为\n)。

    【讨论】:

    • +1 如果你解释 *=+=。 :) (理由:实现 atoi 是用户第一次使用 *=+= 的主要示例。)
    • 总字符串 = 总字符串 * 基数 |||总字符串 = 总字符串 + 数字
    • 我之前已经尝试过,但我的输出仍然关闭。我得到 ABCD (base 16) = 10171274843981 (base 10)
    • @dave:正如我在答案开头提到的那样 - “假设函数 char2int 已正确实现”。你没有在代码中提供,所以我们无从得知...
    • @dave:可能是因为您在每次迭代结束时打印它,而不是在整个循环结束时打印。
    【解决方案2】:

    解决方案:

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

    }

    【讨论】:

      猜你喜欢
      • 2014-03-31
      • 2014-09-03
      • 2013-01-13
      • 1970-01-01
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多