2

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

1
  • Have you taken a look at this reinterpret_cast should be to a char const* Commented Mar 20, 2019 at 12:51

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, and as you have described my problem, I am accepting this. finally, I asked a question in C++ that did not get downvotes at first place :))
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.