数据类型混乱,需要 char 数组中的整数

Data type confusion, need integer from char array

我又一次输入了错误的数据类型。这是一个arduino项目。

我有一个字符数组。最后 9 个字符是 rgb,我把它们当作三胞胎。所以 000255000。

我需要将它们作为整数传递给函数,例如 0、255、0。如果 000 变成 0 我没问题,但我需要 045 变成 45。

我试过投射它们,例如:

blue = (int)message[11];
blue += (int)message[12];
blue += (int)message[13];

那没有用。然而,我可以将它们转换为字符串,我这样做了,然后我尝试了:是的,我知道这不是一个好主意,但值得一试。

char tempBlue[4];
blue.toCharArray(tempGreen, sizeof(tempGreen));
iBlue = atoi(tempGreen);

那也没用。

我不知道该怎么做。我不知道如何(如果可以的话)连接整数,否则我会尝试这样做。

编辑------

我是不是问错了问题。我应该反过来做吗?先连接再连接到整数?我将它们作为角色开始。

要将每个字符转换为其各自的 int,请执行以下操作

int first = message[11] - '0';
int second= message[12] - '0';
int third = message[13] - '0';

要了解其工作原理,您可以在此处查看:Why does subtracting '0' in C result in the number that the char is representing?

要连接整数,您可以使用此函数

unsigned concatenate(unsigned x, unsigned y) {
     unsigned pow = 10;
     while(y >= pow)
         pow *= 10;
     return x * pow + y;        
}

这个函数不是我写的,原来是@TBohne写的here

我会选择:

char *partMessage = (char*)malloc(4);
partMessage[3] = '[=10=]';
strncpy(partMessage, message + 11, 3);
result = (int)strtol(partMessage, NULL, 10);
free(partMessage);

你可以试试这样的

#include <stdio.h>

int main()
{
  // example
  char message[] = { "000255000" };
  int r=0, g=0, b=0;

  // make sure right number of values have been read
  if ( sscanf(message, "%03d%03d%03d", &r, &g, &b ) == 3 )
  {
    printf( "R:%d, G:%d, B:%d\n", r,g,b );
  }
  else
  {
    fprintf(stderr, "failed to parse\n");
  }
}

sscanf 将跳过任何白色 space,因此即使像 message[] = " 000 255 000 "; 这样的字符串也可以工作。

只需手动进行转换:

int convert_digits(char *cp, int count) {
    int result = 0;
    for (int i = 0; i < count; i += 1) {
        result *= 10;
        result += (cp[i] - '0');
    }
    return result;
}

char *input = "000045255";

int main(int ac, char *av[]) {
    printf("r=%d g=%d, b=%d\n",
        convert_digits(cp, 3),
        convert_digits(cp+3, 3),
        convert_digits(cp+6, 3));
}

将字符串转换为数字,然后一次去除 3 位数字。

const char *s = "000255000";
char *endptr;
unsigned long num = strtoul(s, &endptr, 10);

// add error checking on errno, num, endptr) here if desired.

blue = num%1000;
num /= 1000;
green = num%1000;
num /= 1000;
red = num%1000;

// Could add check to insure r,g,b <= 255.