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

Amir-Mousavi
  • 4,273
  • 12
  • 70
  • 123
  • Have you taken a look at [this](https://stackoverflow.com/a/1673536/2935386) reinterpret_cast should be to a `char const*` – harry Mar 20 '19 at 12:51

2 Answers2

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);
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • 1
    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 :)) – Amir-Mousavi Mar 20 '19 at 13:06
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.

Blaze
  • 16,736
  • 2
  • 25
  • 44