简体   繁体   中英

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

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

/* 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

I did it like below, but it concatenates the numeric values of the array and results in something like "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)); which throws exception

In your original cast 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.

Fix:

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

Just leave away the 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. On the other hand, just adding a char to an std::string using += works fine. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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