【问题标题】:convert uint8_t array to string将 uint8_t 数组转换为字符串
【发布时间】:2019-08-11 03:50:52
【问题描述】:

我的项目我有一个结构,它有一个unsigned int array(uint8_t) 类型的成员,如下所示

typedef uint8_t  U8;
typedef struct {
    /* other members */
    U8 Data[8];
} Frame;

收到一个指向Frame 类型变量的指针,在调试期间我在 VS2017 的控制台中看到它如下所示

/* the function signatur */
void converter(Frame* frm){...}

frm->Data   0x20f1feb0 "6þx}\x1òà...   unsigned char[8] // in debug console

现在我想将它分配给一个 8 字节的字符串

我像下面那样做了,但它连接了数组的数值并导致类似"541951901201251242224"

std::string temp;
for (unsigned char i : frm->Data)
{
    temp += std::to_string(i);
}

还尝试了const std::string temp(reinterpret_cast<char*>(frm->Data, 8));,它会引发异常

【问题讨论】:

  • 你看过thisreinterpret_cast 应该是char const*

标签: c++ visual-c++ stdstring unsigned-char uint8t


【解决方案1】:

请不要使用std::to_string。它将数值转换为其字符串表示形式。因此,即使您给它一个char,它也会将其转换为整数并将其转换为该整数的数字表示形式。另一方面,只需使用+=char 添加到std::string 就可以了。试试这个:

int main() {
    typedef uint8_t  U8;
    U8 Data[] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F };
        std::string temp;
        for (unsigned char i : Data)
        {
            temp += i;
        }
        std::cout << temp << std::endl;
}

有关std::string+= 运算符的更多信息和示例,请参阅here

【讨论】:

    【解决方案2】:

    在您原来的演员 const std::string temp(reinterpret_cast&lt;char*&gt;(frm-&gt;Data, 8)); 中,您将右括号放在错误的位置,因此它最终会执行 reinterpret_cast&lt;char*&gt;(8),这就是导致崩溃的原因。

    修复:

    std::string temp(reinterpret_cast<char const*>(frm->Data), sizeof frm->Data);
    

    【讨论】:

    • 非常感谢,正如您所描述的我的问题,我接受了。最后,我在 C++ 中问了一个最初没有被否决的问题 :))
    猜你喜欢
    • 2021-10-09
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    相关资源
    最近更新 更多