我的项目我有一个结构,有一个类型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));
抛出异常
在你原来的演员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);
只需离开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;
}
有关here的std::string
运算符的更多信息和示例,请参阅+=
。