问题描述
我正在尝试在Arduino中创建一个函数,以将字符串转换为字节ascii十六进制值的数组。我几乎不了解c,因此,我为尝试完成我认为必须简单的事情而采取的这种复杂方式表示歉意,但事情确实如此:
输入“ AAA”
输出/预期结果:最终[] = {0x41,0x41,0x41,...}
void enviarMsj(const String& message){
char mensaje[message.length()];
String temp;
char buf[4];
uint16_t final[30];
for(int i = 0; i < message.length(); i++){
temp = "0x" + String(message.charat(i),HEX);
temp.tochararray(buf,5);
final[i]= buf;
}
}
解决方法
使用Arduino的便捷性给人一种错误的印象,那就是您可以开始编写程序而无需过多地学习基本数据类型和C ++,但是如果不了解基本数据类型,则倾向于编写不必要的代码。
msg
的字符数组ABCDEF0123456
是char
的数组,而C ++(和C语言)中的char
从本质上类似于uint8_t
或{ {1}},byte
'A'作为ASCII存储,其十六进制值为char
或十进制为0x41
。
65
因此,如果您执行uint8_t byte_of_char_A = (uint8_t) 'A';
,将获得Serial.print(msg[0],HEX)
的十六进制值。
要创建前缀为41
的c字符串,可以使用旧的sprintf()函数。
0x
这将打印出结果为:
void setup() {
const char msg[]="ABCDEF01234";
Serial.begin(115200);
while (!Serial) {}
char temp[5];
for (int i=0; i<strlen(msg); i++) {
sprintf(temp,"0x%x",msg[i]);
Serial.print(temp);
Serial.print(" ");
}
Serial.println();
}
void loop() {
}
关于代码的另一件事,由于0x41 0x42 0x43 0x44 0x45 0x46 0x30 0x31 0x32 0x33 0x34
上的数据类型不匹配,因此代码无法编译。即使可以成功编译,数组final[i]= buf;
也是一个局部声明的变量,当程序退出该函数时它将消失,因此除了数据类型之外,您还需要了解“变量范围”。
我建议您通读C++ Tutorials。
,我正在尝试了解您要做什么,但是它认为这种方式行不通:
for(int i = 0; i < sizeof(*msg);i++)
{
byte *msgReady[i] = "0x" + ((int(*msg[i]))-36);
}
可能的解决方案:
do
{
char data[5];
data['0'] = '0';
data['1'] = 'x';
// If there should be 2 hex characters
// it is necessary to adapt the calculation
char nibble_high = *msg / 16;
if(nibble_high > 9)
nibble_high = 'A' + (nibble_high - 10);
char nibble_low = *msg % 16;
if(nibble_low > 9)
nibble_low = 'A' + (nibble_low - 10);
// Better write a function that does the conversion
data['2'] = nibble_high;
data['3'] = nibble_low;
data['4'] = '\0'; // Only necessary if copied with string functions
// Copy the data to your msgReady byte array
// can be done with functions in string.h
// or manually
for(unsigned char i=0; i < (sizeof(data) - 1); i++)
{
*msgReady = data[i];
msgReady++;
}
// Increment the address of the message array
msg++;
} while(*msg); // The msg array has to be '\0' terminated