Please see the code snippet below :
#include <iostream>
using namespace std;
int main()
{
uint32_t len, x;
char abc[] = "12345678";
uint8_t *ptr = (uint8_t *)abc;
copy(ptr, ptr + 4, reinterpret_cast<uint32_t*>(&len));
cout << " len: " << len << endl;
}
The output is 49! I would want the output to be 1234. Am I missing something
Your target is a “container” of length 1 (namely, a single object,
len).You are copying four subsequent byte values into this container, which of course fails – in particular, it causes an overflow since the target only has space for a single element.
Other errors in your code (not an exhaustive list):
The first point in particular is relevant since what you actually want to do is parse the number encoded in the first four characters of the string as a decimal number. But what you actually do is copy its character codes.
To parse a number in C++, use as
std::stringstreamor, since C++11,std::stoi