c++ - 字节数组转换为逗号分隔的 int 字符串

标签 c++ arduino

我有一个控制定时器的 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/

相关文章:

c++ - cpp 将 int 分配给字符串恶作剧

c++ - : vector. clear() 或 if(vector.empty()) clear(); 哪个更有效?

c++ - 更改 win32 应用程序标题栏(标题)的颜色

c# - 无法从 'byte[]' 转换为 'byte*'

c - AVR USART通讯

没有库的Arduino伺服器

Android BLE 扫描与 UUID 过滤器列表混淆

c++ - std::map 访问速度太慢?

c++ - LCD液晶程序中几行程序需要说明

c++ - c++中的sqrt函数程序中的错误