C、如何将数组中的数字拆分为 int

C, how to put number split over an array, into int

假设我有 char array[10][0] = '1'[1] = '2'[2] = '3'

我将如何使用 C 从这些索引创建 (int) 123

我希望在 arduino 板上实现这个,它的 SRAM 限制在 2kb 以下。所以机智和效率是关键。


感谢 Sourav Ghosh,我用适合的自定义函数解决了这个问题:

long makeInt(char one, char two, char three, char four){
  char tmp[5];
  tmp[0] = one;
  tmp[1] = two;
  tmp[2] = three;
  tmp[3] = four;

  char *ptr;
  long ret;
  ret = strtol(tmp, &ptr, 10);

  return ret;
}

我想你需要知道的是strtol()。阅读详情 here.

只引用重要部分

long int strtol(const char *nptr, char **endptr, int base);

The strtol() function converts the initial part of the string in nptr to a long integer value according to the given base, which must be between 2 and 36 inclusive, or be the special value 0.

int i = ((array[0] << 24) & 0xff000000) |
                ((array[1] << 16) & 0x00ff0000) |
                ((array[2] << 8) & 0x0000ff00) |
                ((array[3] << 0) & 0x000000ff);

这应该有效

如果您没有 strtol()atoi() 可用的图书馆,请使用此:

int result = 0;
for(char* p = array; *p; )
{    
    result += *p++ - '0';
    if(*p) result *= 10; // more digits to come
}