将uint8_t数组转换为字符串

时间:2019-03-20 12:38:59

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

在该项目中,我有一个结构,该结构具有一个类型为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));引发异常

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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;
}

有关std::string的{​​{1}}运算符的更多信息和示例,请参见here

相关问题