繁体   English   中英

将 uint8_t 数组转换为字符串

[英]convert uint8_t array to string

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

在你原来的演员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;
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM