【问题标题】:How can I add a value with string into char array?如何将带有字符串的值添加到 char 数组中?
【发布时间】:2020-02-27 16:50:56
【问题描述】:

我正在尝试通过 USART 传输数据。
我想发送一个带有值的字符串,例如Temperature: 79 这个 79 在 int 变量中。

我尝试了什么:

uint8_t *buffer[] = {(uint8_t*)"\nSW version 001\0",(uint8_t*)"\nTemperature:"};
uint8_t **ptr = buffer;
io_write(io, *buffer ,100); 

输出:

SW versio 001 Temperature:

我不知道如何将值合并到数组中。我该怎么做?

【问题讨论】:

  • 您可以使用哪些功能?你写这个干什么?
  • *buffer ,100); - 这是无效和未定义的行为。您不能假设两个指针会彼此相邻。为什么要传输零字节?

标签: c arrays string embedded usart


【解决方案1】:

使用snprintf。在一次通话中:

int temperature = 12345;
char buffer[200];
const int len = snprintf(buffer, sizeof(buffer), "\nSW verison 001\nTemperature: %d\n", temperature);
io_write(io, buffer, len);

在内存和空间受限的裸机嵌入式设备上,*printf 系列功能可能不可用或使用不合理。您将不得不推出自己的“int_to_string”-ish 转换函数。您可以找到integer_to_string 函数,例如in this answer on stackoverflow

// NOT MY WORK, this function was written by @asveikau
int
integer_to_string(char *buf, size_t bufsize, int n)
{
   char *start;

   // Handle negative numbers.
   //
   if (n < 0)
   {
      if (!bufsize)
         return -1;

      *buf++ = '-';
      bufsize--;
   }

   // Remember the start of the string...  This will come into play
   // at the end.
   //
   start = buf;

   do
   {
      // Handle the current digit.
      //
      int digit;
      if (!bufsize)
         return -1;
      digit = n % 10;
      if (digit < 0)
         digit *= -1;
      *buf++ = digit + '0';
      bufsize--;
      n /= 10;
   } while (n);

   // Terminate the string.
   //
   if (!bufsize)
      return -1;
   *buf = 0;

   // We wrote the string backwards, i.e. with least significant digits first.
   // Now reverse the string.
   //
   --buf;
   while (start < buf)
   {
      char a = *start;
      *start = *buf;
      *buf = a;
      ++start;
      --buf;
   }

   return 0;
}

有了这样的功能,你可以:

int temperature = 12345;
char buffer[200] = "\nSW verison 001\nTemperature: ";
integer_to_string(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), temperature);
strcat(buffer, "\n");
io_write(io, buffer, strlen(buffer));

【讨论】:

  • sprintf 当你有 8kB FLASH 并且 sprintf 需要 6kB 时非常棒。对于嵌入式来说不是很好的建议。编写 uCs 时应避免使用 printf 和朋友
  • 好吧,有些人会争辩说应该到处避免使用printf。让我们进行培训,我将尝试编写自己的itos 函数,让我们看看...
  • 我真的不认为 OP 有可用的标准 C 库...
【解决方案2】:

您需要编写自己的函数。例如(不是我的,但被广泛使用):

https://godbolt.org/z/MoP7pn

/*
******************************************************************************
File:     tiny_printf.c
Info:     Generated by Atollic TrueSTUDIO 9.2.0   2020-02-27

Abstract: Atollic TrueSTUDIO Minimal iprintf/siprintf/fiprintf
          and puts/fputs.
          Provides aliased declarations for printf/sprintf/fprintf
          pointing to *iprintf variants.

          The argument contains a format string that may include
          conversion specifications. Each conversion specification
          is introduced by the character %, and ends with a
          conversion specifier.

          The following conversion specifiers are supported
          cdisuxX%

          Usage:
          c    character
          d,i  signed integer (-sign added, + sign not supported)
          s    character string
          u    unsigned integer as decimal
          x,X  unsigned integer as hexadecimal (uppercase letter)
          %    % is written (conversion specification is '%%')

          Note:
          Character padding is not supported

The MIT License (MIT)
Copyright (c) 2018 STMicroelectronics

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

******************************************************************************
*/

/* Includes */
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

/* Create aliases for *printf to integer variants *iprintf */
__attribute__ ((alias("siprintf"))) int sprintf(char* str, const char *fmt, ...);

/* External function prototypes (defined in syscalls.c) */
extern int _write(int fd, char *str, int len);

/* Private function prototypes */
void ts_itoa(char **buf, unsigned int d, int base);
int ts_formatstring(char *buf, const char *fmt, va_list va);
int ts_formatlength(const char *fmt, va_list va);

/* Private functions */

/**
**---------------------------------------------------------------------------
**  Abstract: Convert integer to ascii
**  Returns:  void
**---------------------------------------------------------------------------
*/
void ts_itoa(char **buf, unsigned int d, int base)
{
    int div = 1;
    while (d/div >= base)
        div *= base;

    while (div != 0)
    {
        int num = d/div;
        d = d%div;
        div /= base;
        if (num > 9)
            *((*buf)++) = (num-10) + 'A';
        else
            *((*buf)++) = num + '0';
    }
}

/**
**---------------------------------------------------------------------------
**  Abstract: Writes arguments va to buffer buf according to format fmt
**  Returns:  Length of string
**---------------------------------------------------------------------------
*/
int ts_formatstring(char *buf, const char *fmt, va_list va)
{
    char *start_buf = buf;
    while(*fmt)
    {
        /* Character needs formating? */
        if (*fmt == '%')
        {
            switch (*(++fmt))
            {
              case 'c':
                *buf++ = va_arg(va, int);
                break;
              case 'd':
              case 'i':
                {
                    signed int val = va_arg(va, signed int);
                    if (val < 0)
                    {
                        val *= -1;
                        *buf++ = '-';
                    }
                    ts_itoa(&buf, val, 10);
                }
                break;
              case 's':
                {
                    char * arg = va_arg(va, char *);
                    while (*arg)
                    {
                        *buf++ = *arg++;
                    }
                }
                break;
              case 'u':
                    ts_itoa(&buf, va_arg(va, unsigned int), 10);
                break;
              case 'x':
              case 'X':
                    ts_itoa(&buf, va_arg(va, int), 16);
                break;
              case '%':
                  *buf++ = '%';
                  break;
            }
            fmt++;
        }
        /* Else just copy */
        else
        {
            *buf++ = *fmt++;
        }
    }
    *buf = 0;

    return (int)(buf - start_buf);
}


/**
**---------------------------------------------------------------------------
**  Abstract: Calculate maximum length of the resulting string from the
**            format string and va_list va
**  Returns:  Maximum length
**---------------------------------------------------------------------------
*/
int ts_formatlength(const char *fmt, va_list va)
{
    int length = 0;
    while (*fmt)
    {
        if (*fmt == '%')
        {
            ++fmt;
            switch (*fmt)
            {
              case 'c':
                  va_arg(va, int);
                  ++length;
                  break;
              case 'd':
              case 'i':
              case 'u':
                  /* 32 bits integer is max 11 characters with minus sign */
                  length += 11;
                  va_arg(va, int);
                  break;
              case 's':
                  {
                      char * str = va_arg(va, char *);
                      while (*str++)
                          ++length;
                  }
                  break;
              case 'x':
              case 'X':
                  /* 32 bits integer as hex is max 8 characters */
                  length += 8;
                  va_arg(va, unsigned int);
                  break;
              default:
                  ++length;
                  break;
            }
        }
        else
        {
            ++length;
        }
        ++fmt;
    }
    return length;
}

/**
**===========================================================================
**  Abstract: Loads data from the given locations and writes them to the
**            given character string according to the format parameter.
**  Returns:  Number of bytes written
**===========================================================================
*/
int siprintf(char *buf, const char *fmt, ...)
{
    int length;
    va_list va;
    va_start(va, fmt);
    length = ts_formatstring(buf, fmt, va);
    va_end(va);
    return length;
}

【讨论】:

    猜你喜欢
    • 2021-03-18
    • 1970-01-01
    • 2011-04-03
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多