将char *转换为uint16_t c ++

时间:2017-09-09 07:58:12

标签: c++ arduino esp8266 arduino-esp8266

尝试将char *或字符串转换为uint16_t

转换这个:

char* rawData = "9000, 4500, 650, 550, 650, 1650, 600, 550, 650, 550, 600, 
1650, 650, 550, 600, 1650, 650, 1650, 650, 1650, 600, 550, 650, 1650, 650, 
1650, 650, 550, 600, 1650, 650, 1650, 650, 550, 650, 550, 650, 1650, 650, 
550, 650, 550, 650, 550, 600, 550, 650, 550, 650, 550, 650, 1650, 600, 550, 
650, 1650, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 600";


char* rawData_leng = "67";

进入这个:

uint16_t blawData[67] = {9000, 4500, 650, 550, 650, 1650, 600, 550, 650, 550,
                    600, 1650, 650, 550, 600, 1650, 650, 1650, 650, 1650,
                    600, 550, 650, 1650, 650, 1650, 650, 550, 600, 1650,
                    650, 1650, 650, 550, 650, 550, 650, 1650, 650, 550,
                    650, 550, 650, 550, 600, 550, 650, 550, 650, 550,
                    650, 1650, 600, 550, 650, 1650, 650, 1650, 650, 1650,
                    650, 1650, 650, 1650, 650, 1650, 600};

2 个答案:

答案 0 :(得分:1)

使用strtok

char rawData[] = "9000, 4500, 650, 550, 650, 1650, 600, 550, 650, 550, 600, 1650, 650, 550, 600, 1650, 650, 1650, 650, 1650, 600, 550, 650, 1650, 650, 1650, 650, 550, 600, 1650, 650, 1650, 650, 550, 650, 550, 650, 1650, 650, 550, 650, 550, 650, 550, 600, 550, 650, 550, 650, 550, 650, 1650, 600, 550, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 600";
size_t rawDataLength = 67;

uint16_t blawData[rawDataLength];
char *token = strtok(rawData, ", ");
for (size_t i = 0; i < rawDataLength; ++i) {
    blawData[i] = atoi(token);
    token = strtok(nullptr, ", ");
}
//assert(token == nullptr);

Ideone

答案 1 :(得分:0)

char* rawData = "9000, 4500, 650, 550, 650, 1650, 600, 550, 650, 550, 600, 
1650, 650, 550, 600, 1650, 650, 1650, 650, 1650, 600, 550, 650, 1650, 650, 
1650, 650, 550, 600, 1650, 650, 1650, 650, 550, 650, 550, 650, 1650, 650, 
550, 650, 550, 650, 550, 600, 550, 650, 550, 650, 550, 650, 1650, 600, 550, 
650, 1650, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 650, 1650, 600";

const char s[3] = ", ";
char *token;
uint16_t crawlCall[200] = {};
int while_count = 0;
token = strtok(rawData, s);
while( token != NULL ) 
{
  int i =  atoi (token);
  crawlCall[while_count] = i;
  token = strtok(NULL, s);
  while_count++;
}

我是所有这一切的新手,所以它可能不是最佳的,但crawlCall是我正在寻找的uint16_t值。