将uint8_t数组转换为字符串

问题描述 投票:1回答:2

我的项目我有一个结构,有一个类型unsigned int arrayuint8_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));抛出异常

c++ visual-c++ stdstring unsigned-char uint8t
2个回答
1
投票

在你原来的演员const std::string temp(reinterpret_cast<char*>(frm->Data, 8));你把右括号放在错误的地方,这样它最终做了reinterpret_cast<char*>(8),这就是崩溃的原因。

固定:

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

0
投票

只需离开std::to_string。它将数值转换为字符串表示形式。因此,即使你给它一个char,它也会将它转换为整数并将其转换为该整数的数字表示。另一方面,只需使用charstd::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;
}

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

© www.soinside.com 2019 - 2024. All rights reserved.