gpt4 book ai didi

c++ - 在C++中将uint8_t数组转换为字符串

转载 作者:行者123 更新时间:2023-12-02 10:04:38 25 4
gpt4 key购买 nike

这可以标记为已解决。问题是打印宏。 ESP_LOGx无法输出c++字符串。

我正在尝试将uin8_t数组转换为c++中的字符串。
数组是在头文件中定义的,如下所示:

uint8_t mypayload[1112];

打印数组本身是可行的,所以我确定它不是空的。

现在我正在尝试将其转换为字符串:
string qrData; 
std::string qrData(reinterpret_cast<char const*>(mypayload), sizeof mypayload);

我也尝试过: qrData = (char*)mypayload;
打印字符串将得到5个随机字符。

有人暗示我做错了吗?

最佳答案

到目前为止,唯一正确的注释来自“一些程序员老兄”。因此,所有功劳归于他。

来自Ian4264的评论完全是错误的。当然,您可以进行reinterpret_cast。

请阅读here有关std::string的构造函数。您正在使用构造函数编号4。描述为:

4) Constructs the string with the first count characters of character string pointed to by s. s can contain null characters. The length of the string is count. The behavior is undefined if [s, s + count) is not a valid range.



因此,即使字符串包含0个字符(C样式字符串“终结符”),也会复制uint8_t数组的所有字节。并且,如果您打印字符串,则它将打印所有字符,甚至在'\ 0'之后的所有不可打印字符。

那也许是你的“随机”角色。因为“终止符”之后的字符串很可能包含未初始化的值。

您应该考虑使用构造函数编号5

5) Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if [s, s + Traits::length(s)) is not a valid range.



如果需要添加字节,也可以。 std::string可以动态增长。

顺便说一句:您确实定义了“std::string qrData” double 值,它将不会编译

关于c++ - 在C++中将uint8_t数组转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60898360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com