Mat*_*lli 2 c c++ memory-management arduino
我在 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;
}
Run Code Online (Sandbox Code Playgroud)
toCharArray () 函数不会将字符串转换为字符数组。Serial.print (c) 返回空打印。我不知道我能做什么。
更新:您的问题:String -> char*转换:
String.toCharArray(char* buffer, int length) 想要一个字符数组缓冲区和缓冲区的大小。
具体来说 - 您的问题是:
char* c 是一个从未初始化的指针。length应该是缓冲区的大小。字符串知道它有多长。因此,运行它的更好方法是:
char c[20];
s.toCharArray(c, sizeof(c));
Run Code Online (Sandbox Code Playgroud)
或者,您可以初始化c用malloc,但你不得不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);
Run Code Online (Sandbox Code Playgroud)
除非出于学术目的需要此代码,否则您应该使用标准库提供的机制,而不是重新发明轮子。
String(int, HEX) 返回您要转换的整数的十六进制值Serial.print接受String作为参数