将 uint8_t 数组转换为字符串

convert uint8_t array to string

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

只需离开 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

在您原来的转换 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);