Question

Let's start off by stating that I have 0 xp with C++.

I have a byte array which is filled with data.

Example:

byte 0: 1
byte 1: 75
byte 2: 125
byte 3: 66
byte 4: 114
byte 5: 97
byte 6: 109

I have a CString in C++ which is supposed to get all the bytes. But bytes 0-2 are supposed to be int's and bytes 3-6 are supposed to be ASCII characters.

When I read the bytes and place them in the CString the following will be shown:

" K}Bram"

Only the "Bram" part is correct. The output should be:

"175125Bram"

I have a switch on the byte array's index so I can control the bytes. For bytes 0-2 I use the following code:

receiveStr += "" + (int)buffer[i]);

For the bytes 3-6 I use the following code:

if ((buffer[i] >= 0x20 && buffer[i] <= 0x7E) || (buffer[i] == '\r') || (buffer[i] == '\n') || (buffer[i] == '\t'))
{
    receiveStr += buffer[i];
}
else
{
    // Display the invalid character placeholder (square)
    receiveStr += (char)0x7F;
}

How can I 'convert' the first bytes to int's?

Was it helpful?

Solution

What does it mean when you call 'convert to int'? How should it look like in the output? Your first 3 bytes already stored as int values, but its representation is still ascii characters.

If it meant to be string like "175125Bram" then solution should be like this

#include <sstream>

stringstream ss;
ss << buffer[0] << buffer[1] << buffer[2];
receiveStr += ss.str();

OTHER TIPS

There's many ways.. Maybe itoa, a non-standard function, is the most well-known one. snprintf/swprintf also can be solution. They require a fixed-size buffer, but maybe you can know appropriate size in this case.

In C++11, there is std::to_string/std::to_wstring function. it converts numbers into std::string/std::wstring.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top