我有一个控制定时器的 Arduino。定时器的设置存储在字节数组中。我需要将数组转换为字符串,以便在外部 Redis 服务器上设置字符串。
因此,我有许多不同长度的字节数组,需要将它们转换为字符串,以作为参数传递给需要 char[]
的函数。我需要用逗号分隔这些值并以“\0”结尾。
byte timer[4] {1,5,23,120};
byte timer2[6] {0,0,0,0,0,0}
我已经成功地使用 sprintf()
手动为每个数组执行此操作,如下所示
char buf[30];
for (int i=0;i<5;i++){ buf[i] = (int) timer[i]; }
sprintf(buf, "%d,%d,%d,%d,%d",timer[0],timer[1],timer[2],timer[3],timer[4]);
这给了我一个输出字符串buf
:1,5,23,120
但我必须在 sprintf() 中使用固定数量的“占位符”。
我想提出一个可以传递数组名称的函数(例如timer[]
),并且可以构建一个字符串,可能使用“variable”的for循环lengths”(取决于要“处理”的特定数组)和许多 strcat()
函数。我尝试了几种方法来做到这一点,但它们对编译器和我来说都没有意义!
我应该往哪个方向寻找?
最佳答案
这是用普通 C 语言可以实现的低技术方法。
char* toString(byte* bytes, int nbytes)
{
// Has to be static so it doesn't go out of scope at the end of the call.
// You could dynamically allocate memory based on nbytes.
// Size of 128 is arbitrary - pick something you know is big enough.
static char buffer[128];
char* bp = buffer;
*bp = 0; // means return will be valid even if nbytes is 0.
for(int i = 0; i < nbytes; i++)
{
if (i > 0) {
*bp = ','; bp++;
}
// sprintf can have errors, so probably want to check for a +ve
// result.
bp += sprintf(bp, "%d", bytes[i])
}
return buffer;
}
关于c++ - 字节数组转换为逗号分隔的 int 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48310713/