如何在Arduino中将字符串转换为char*
How to convert a String to a char * in 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;
}
toCharArray()函数没有将字符串转换为char数组。Serial.print(c)正在返回空打印。我不知道我能做什么。
更新:您的问题re:String -> char*
转换:
String.toCharArray(char* buffer, int length)
想要一个字符数组缓冲区和缓冲区的大小。
具体来说,你的问题是:
char* c
是一个从不初始化的指针- 假定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;
}
}
相关文章:
- 将无符号char*转换为std::istream*C++
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 使用char类型将decimal转换为string,将string转换为decimal
- 如何在对<char>C++程序进行逆向工程的同时将 std::basic_string 转换为 Rust 可读值?
- 将函数参数"const char*"转换为"std::string_view"是
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何在不强制转换每个参数的情况下删除初始值设定项列表中从 int 到 char 的缩小转换?
- C ++如何在使用"tolower"时将char转换为int
- 有没有办法在C++的赋值中将"char**"转换为"double"?
- 如何使用多次 memcpy 转换回 std::vector<unsigned char>?
- 将"uint8_t"(从套接字读取)隐式转换为"char"安全吗
- JavaCPP 错误:无法将参数"1"的"char*"转换为"Abc*
- 将传入的网络"char*"数据转换为"uint8_t"并返回的安全方法是什么?
- 转换char*时的值不同
- Boost Python 不会自动转换 char* 数据成员
- 除了转换char*之外,还有更好的方法来获得一个变量值吗?
- 如何跨平台转换char*到long long(64位)
- 用atof转换char数组中的浮点数
- C转换char[]为时间戳;