如何在Arduino中将字符串转换为char*

How to convert a String to a char * in Arduino?

本文关键字:转换 char 字符串 Arduino      更新时间:2023-10-16

我正在Arduino中执行一个将整数转换为十六进制char*的函数,但我遇到了无法将String转换为char*的问题。也许如果有一种方法可以为char*动态分配内存,我就不需要类String了。

char *ToCharHEX(int x)
{
String s;
int y = 0;
int z = 1;
do
{
if (x > 16)
{
y = (x - (x % 16)) / 16;
z = (x - (x % 16));
x = x - (x - (x % 16));
}
else
{
y = x;
}
switch (y)
{
case 0:
s += "0";
continue;
case 1:
s += "1";
continue;
case 2:
s += "2";
continue;
case 3:
s += "3";
continue;
case 4:
s += "4";
continue;
case 5:
s += "5";
continue;
case 6:
s += "6";
continue;
case 7:
s += "7";
continue;
case 8:
s += "8";
continue;
case 9:
s += "9";
continue;
case 10:
s += "A";
continue;
case 11:
s += "B";
continue;
case 12:
s += "C";
continue;
case 13:
s += "D";
continue;
case 14:
s += "E";
continue;
case 15:
s += "F";
continue;
}
}while (x > 16 || y * 16 == z);
char *c;
s.toCharArray(c, s.length());
Serial.print(c);
return c;
}

toCharArray()函数没有将字符串转换为char数组。Serial.print(c)正在返回空打印。我不知道我能做什么。

更新:您的问题re:String -> char*转换:

String.toCharArray(char* buffer, int length)想要一个字符数组缓冲区和缓冲区的大小。

具体来说,你的问题是:

  1. char* c是一个从不初始化的指针
  2. 假定CCD_ 4是缓冲器的大小。绳子知道它有多长

因此,更好的运行方式是:

char c[20];
s.toCharArray(c, sizeof(c));

或者,您可以使用malloc初始化c,但之后必须使用free。使用堆栈进行类似的操作可以节省时间并使事情变得简单。

参考:https://www.arduino.cc/en/Reference/StringToCharArray


代码中的意图:

这基本上是一个重复的问题:https://stackoverflow.com/a/5703349/1068537

参见Nathan的链接答案:

// using an int and a base (hexadecimal):
stringOne =  String(45, HEX);   
// prints "2d", which is the hexadecimal version of decimal 45:
Serial.println(stringOne);  

除非出于学术目的需要此代码,否则您应该使用标准库提供的机制,而不是重新发明轮子。

  • String(int, HEX)返回要转换的整数的十六进制值
  • Serial.print接受String作为自变量
char* string2char(String command){
if(command.length()!=0){
char *p = const_cast<char*>(command.c_str());
return p;
}
}