代码之家  ›  专栏  ›  技术社区  ›  GAVD

在C++中将uint8的数组转换为字符串,以便在一行中打印

c++
  •  0
  • GAVD  · 技术社区  · 8 年前

    我有任务打印一个数组 uint8_t 在一行中并使用给定的日志函数,该函数在一行中打印每条消息。所以,我想我必须合并字符串中的每个元素并打印出来。我试着用 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
    

    看来效果不错。但今天,我得到了奇怪的日志:

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

    我检查了ascii表 https://www.asciitable.com/ 看看它是一些字节,比如0x01,0x03。我想问题是 %s ,通常,我用 %x 打印数组的每个元素。

    我怎样才能解决这个问题?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Some programmer dude    8 年前

    使用格式化输出运算符时 << ,它将打印字符 作为 角色。您需要将这些值转换为 unsigned 要能够打印其实际整数值:

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