简体   繁体   English

在C ++中将uint8_t数组转换为字符串以在一行中打印

[英]Convert array of uint8_t to string in c++ to print in one line

I have the task print an array of uint8_t in one line and using the given log function which is print each message in one line. 我的任务是在一行中打印uint8_t数组,并使用给定的日志功能在一行中打印每条消息。 So, I think I must merge every element in a string and print. 因此,我认为我必须合并字符串中的每个元素并进行打印。 I try to use std::stringstream 我尝试使用std::stringstream

uint8_t array[512];
std::stringstream ss;
for (int i = 0; i < array_len; i++)
{
    ss << "0x" << std::hex << array[i] << ", ";
}
log_given_print("%s", ss.str().c_str()); // in fact you can replace by printf

It seems to work well. 看来运作良好。 But today, I get the strange log: 但是今天,我得到了奇怪的日志:

0xETX, 0xSOH, 0x%, 0xN, 0x

I checked the ascii table https://www.asciitable.com/ and see that it is some bytes like 0x01, 0x03. 我检查了ascii表https://www.asciitable.com/ ,发现它是一些字节,如0x01、0x03。 I think the problem is %s , normally, I used %x to print each element of array. 我认为问题是%s ,通常,我使用%x来打印数组的每个元素。

How can I fix this problem? 我该如何解决这个问题?

When using the formatted output operator << , it will print characters as characters. 使用格式化的输出运算符<< ,它将字符打印字符。 You need to convert the values to eg unsigned to be able to print its actual integer value: 您需要将值转换为例如unsigned才能打印其实际整数值:

ss << "0x" << std::hex << static_cast<unsigned>(array[i]) << ", ";

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

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