【问题标题】:Array of bytes into a string of comma separated int字节数组转换成逗号分隔的 int 字符串
【发布时间】:2018-01-17 22:00:17
【问题描述】:

我有一个控制计时器的 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[]),它会构建一个字符串,可能使用“可变长度”的for循环(取决于特定的到“处理”的数组)和许多strcat() 函数。我尝试了几种方法来做到这一点,但它们对编译器和我都没有意义!

我应该往哪个方向寻找?

【问题讨论】:

  • timer[4] 超出范围。
  • sprintf 返回字符数。您可以相应地将指针移动到 buf 并执行下一个值,依此类推。只要确保缓冲区足够大。并在第二个等之前手动添加逗号
  • arduino 语言是 C++
  • 问题被标记为c++,但代码(和答案)都在c 中。 c++ 的解决方案是使用 std::ostringstream 来格式化循环中的字节。

标签: c++ arduino


【解决方案1】:

这是您可以在普通 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;
} 

【讨论】:

  • 很好 - 避免 strcat() 重新遍历字符串。我也喜欢nbytes == 0时处理case,所以推荐char* bp = buffer; *bp = '\0';
  • @chux 完美的错误如何蔓延的例子。一切看起来都不错,cmets 提到要调整大小等,但如果你第一次通过 boom 传递nbytes = 0。我猜另一个明显的解决方法(留给读者作为练习)是对参数进行空指针检查。
【解决方案2】:

一个实现,假设timer 是一个数组(否则,必须将大小作为参数传递),并对逗号进行特殊处理。

基本上,在临时缓冲区中打印整数,然后连接到最终缓冲区。 Pepper 在需要的地方加逗号。

请注意,输出缓冲区的大小未经测试。

#include <stdio.h>
#include <strings.h>

typedef unsigned char byte;

int main()
{
   byte timer[4] = {1,5,23,120};
   int i;

   char buf[30] = "";
   int first_item = 1;

   for (i=0;i<sizeof(timer)/sizeof(timer[0]);i++)
   {
      char t[10];
      if (!first_item)
      {
         strcat(buf,",");   
      }
      first_item = 0;

      sprintf(t,"%d",timer[i]);
      strcat(buf,t);
    }

   printf(buf);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    相关资源
    最近更新 更多