简体   繁体   English

将 uint8_t 数组转换为字符串

[英]convert uint8_t array to string

I the project I have a struct that has one member of type unsigned int array ( uint8_t ) like below我的项目我有一个结构,它有一个unsigned int arrayuint8_t )类型的成员,如下所示

typedef uint8_t  U8;
typedef struct {
    /* other members */
    U8 Data[8];
} Frame;

a pointer to a variable of type Frame is received that during debug I see it as below in console of VS2017收到一个指向Frame类型变量的指针,在调试期间我在 VS2017 的控制台中看到它如下

/* the function signatur */
void converter(Frame* frm){...}

frm->Data   0x20f1feb0 "6þx}\x1òà...   unsigned char[8] // in debug console

now I want to assign it to an 8byte string现在我想将它分配给一个 8 字节的字符串

I did it like below, but it concatenates the numeric values of the array and results in something like "541951901201251242224"我像下面那样做,但它连接数组的数值并产生类似"541951901201251242224"

std::string temp;
for (unsigned char i : frm->Data)
{
    temp += std::to_string(i);
}

also tried const std::string temp(reinterpret_cast<char*>(frm->Data, 8));也试过const std::string temp(reinterpret_cast<char*>(frm->Data, 8)); which throws exception抛出异常

In your original cast const std::string temp(reinterpret_cast<char*>(frm->Data, 8));在你原来的演员const std::string temp(reinterpret_cast<char*>(frm->Data, 8)); you put the closing parenthesis in the wrong place, so that it ends up doing reinterpret_cast<char*>(8) and that is the cause of the crash.您将右括号放在错误的位置,因此它最终会执行reinterpret_cast<char*>(8) ,这就是崩溃的原因。

Fix:使固定:

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

Just leave away the std::to_string .只需离开std::to_string It converts numeric values to their string representation.它将数值转换为其字符串表示形式。 So even if you give it a char , it will just cast that to an integer and convert it to the numerical representation of that integer instead.因此,即使您给它一个char ,它也会将其转换为整数并将其转换为该整数的数字表示形式。 On the other hand, just adding a char to an std::string using += works fine.另一方面,只需使用+=char添加到std::string Try this:尝试这个:

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;
}

See here for more information and examples on std::string 's += operator.有关std::string+=运算符的更多信息和示例,请参见此处

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

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