【问题标题】:How to convert string to int in pic controller如何在 pic 控制器中将字符串转换为 int
【发布时间】:2019-06-06 11:04:24
【问题描述】:

如何将字符串转换为 int 以在 LCD 上显示。我尝试使用itoa,即使添加<stdlib.h>,编译器也不支持。

这是我的代码:

【问题讨论】:

  • 如果你想在 LCD 上显示一个数字,那么你不希望它是一个 int。您希望它是代表 int 的字符串。您真的在问如何将 int 转换为字符串吗?
  • 为什么要尝试使用 itoa(),它将 int 转换为字符串,而不是将字符串转换为 int。您需要 strtol() 代替,这是自 C89 以来的标准函数,因此更有可能可用。 C99 也定义了 atoi()。
  • 但是,您似乎需要解决这个问题,并且无论如何您都打算转换为字符串。
  • @maxy 你认为 00010000 等于 10 的底数是多少?
  • @maxy 好吧,我下面写的不是吗?甚至克利福德提到的功能?另外,请展示您已经尝试过的内容。

标签: c string embedded pic


【解决方案1】:
#include <stdio.h>
#include <string.h>    

int stringToInt(char * s){
    int res = 0;
    for(size_t i=0; i<strlen(s); i++)
        res = (res * 10) + (s[i] - '0');
    return res;
}

int main(void){
    printf("%d\n", stringToInt("256"));
    return(0);
}

这不适用于超过 int 可以存储的数字。或者只使用 stdlib.h 中的 strltol / strtoul / atoi。

【讨论】:

    【解决方案2】:

    您无需任何转换即可轻松地在 LCD 上显示字符串。 其次,我在 MplabX 中检查了 itoa,它工作得很好!

    总而言之,这一切都很好:

    int toString(char a[]) {
      int c, sign, offset, n;
    
      if (a[0] == '-') {  // Handle negative integers
        sign = -1;
      }
    
      if (sign == -1) {  // Set starting position to convert
        offset = 1;
      }
      else {
        offset = 0;
      }
    
      n = 0;
    
      for (c = offset; a[c] != '\0'; c++) {
        n = n * 10 + a[c] - '0';
      }
    
      if (sign == -1) {
        n = -n;
      }
    
      return n;
    }
    

    【讨论】:

      【解决方案3】:

      xc 编译器支持iota
      您必须在 MPLABx 中进行以下设置:

      项目属性/全局选项,然后取消选择使用旧版 libc

      【讨论】:

        猜你喜欢
        • 2012-07-04
        • 2011-06-18
        • 2010-09-17
        • 1970-01-01
        • 1970-01-01
        • 2015-11-12
        • 2018-05-08
        • 1970-01-01
        相关资源
        最近更新 更多