简体   繁体   English

将uint8_t转换为ascii字符串C

[英]Convert uint8_t to an ascii string C

Given the following function 赋予以下功能

UART_write(UART_Handle handle, const void *buffer, size_t size);

I want to send via uart a int8_t value ( log it ) 我想通过uart发送一个int8_t值(记录它)

What i tried: 我试过的

int8_t value;
UART_write(uart, value, strlen(value));

const char *echoPrompt = (char *)value;
UART_write(uart, echoPrompt, sizeof(echoPrompt));

const char echoPrompt2[] = {value};
UART_write(uart, echoPrompt2, sizeof(echoPrompt2));

const char* buff = value;
UART_write(uart, value, strlen(value));

The best i got is logging the hex value 我得到的最好的是记录十六进制值

Exemple of how the uart_write function works: In orded to log "12" what I need to do is uart_write函数的工作方式示例:为了记录“ 12”,我需要做的是

   const uint8_t value[] = {0x31, 0x32};
   UART_write(uart, value, sizeof(value));

So my question is, how to log my int8_t variable ( I need to log negative numbers as well) 所以我的问题是,如何记录我的int8_t变量(我也需要记录负数)

You will need to convert your integer to string. 您将需要将整数转换为字符串。

snprintf is a standard way to do this, if your libc provides it. 如果您的libc提供了此功能,则snprintf是执行此操作的标准方法。

Convert uint8_t to an ascii string C 将uint8_t转换为ascii字符串C

Determine the maximum string size needed for any value of that type. 确定该类型的任何值所需的最大字符串大小。 Is there a better way to size a buffer for printing integers? 有没有更好的方法来设置用于打印整数的缓冲区的大小?

#define UINT_BUFFER10_SIZE(type) (1 + (CHAR_BIT*sizeof(type)*LOG10_2_N)/LOG10_2_D + 1)

Form the buffer 形成缓冲区

char buf[UINT_BUFFER10_SIZE(value)];

"Print" the uint8_t to the buffer. uint8_t “打印”到缓冲区。

int len = sprintf(buf, "%d", value);
// or pedantically
int len = snprintf(buf, sizeof buf, "%" PRId8, value);  // see <inttypes.h>
assert(len >= 0 && (unsigned)len < sizeof buf);

Send it 发送

UART_write(uart, buf, len);

how to log my int8_t variable 如何记录我的int8_t变量

#define INT_BUFFER10_SIZE(type) (2 + ((CHAR_BIT*sizeof(type)-1)*LOG10_2_N)/LOG10_2_D + 1)
char buf[INT_BUFFER10_SIZE(ivalue)];
int len = sprintf(buf, "%d", ivalue);
UART_write(uart, buf, len);

IMO, code should add a helper function to send a string IMO,代码应添加一个辅助函数来发送字符串

void UART_write_str(UART_Handle handle, const char *str) {
  UART_write(uart, str, strlen(str));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM