Search code examples
c++visual-c++stdstringunsigned-charuint8t

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


Solution

  • 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);