繁体   English   中英

结合数组元素Arduino

[英]Combining Array Elements Arduino

新手在这里。 我正在尝试将数组元素合并为一个整数。

我想将数据元素11到13合并为一个存储在CombinedArray中的单个数字。 期望的结果将是CombinedArray [1] = 123。

uint8_t data[32];
uint8_t combinedArray[2];
data[11] = {'1'};
data[12] = {'2'};
data[13] = {'3'};

任何帮助将非常感激。 我相信需要转换数据类型才能将其连接起来。

您可以使用var代替uint8_t吗?

像这样分配给combinedArray:

combinedArray[1] = data[11] + data[12] + data[13]

您实际上已经在data []中使用了字符串。 “ 1”是字符串,1是数字。

你应该能够做

uint8_t data[32];
uint8_t combinedArray[2];
data[11] = {'1'};
data[12] = {'2'};
data[13] = {'3'};
String result = data[11] + data[12] + data[13];
//then you can convert that to a char array by doing result.toChars();
//or converty the result by doing Integer.parseInt(result);
//you WILL have to use chars instead because they will concatenate correctly
//because uint8_t is not a character its a number so when you concatenate              
//them you add the two ascii values together

简单的十进制(以ASCII格式)到十进制(数字)的转换就足够了:

combinedArray[1] = 0;             // value must be defined
for (uint8_t * ptr = data+11; ptr != data+14; ++ptr) {
  combinedArray[1] *= 10;         // move previous value by one digit to the left (ie. 12 => 120)
  combinedArray[1] += *ptr - '0'; // substract ascii value of '0' from character to get value and add it to the result
}

如果使用字符设置data数组中的元素是错误的,那么您必须删除- '0'这样它才能使用正确的值:
现在,您在data[11] = {'1'};有字符'1' data[11] = {'1'}; 值为49(字符“ 1”的ASCII值)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM