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

时间:2015-06-10 20:44:57

标签: c arduino

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

我有一个char数组。最后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);

那也行不通。

我迷失了如何做到这一点。我不知道如何(如果可以)连接整数或我会尝试过。

EDIT ------

我问错了问题。我应该以相反的方式做这件事。首先连接然后连接到整数?我把它们作为角色开始。

5 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

我会选择:

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

答案 2 :(得分:0)

你可以尝试这样的事情

#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将跳过任何空格,因此即使像message[] = " 000 255 000 ";这样的字符串也能正常工作。

答案 3 :(得分:0)

只需手动进行转换:

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

答案 4 :(得分:0)

将字符串转换为数字,然后一次数字地删除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.