'convert vector of 4 bytes into int c++
my function read_address always returns a vector of 4 bytes
for other usecases it is a vector and not const array
in this use case I always return 4 bytes
std::vector<uint8_t> content;
_client->read_address(start_addr, sizeof(int), content);
uint32_t res = reinterpret_cast<uint32_t>(content.data());
return res;
here is the vector called content

it is always the same values
however the value of "res" is always changing to random numbers Can you please explain my mistake
Solution 1:[1]
Your code is casting the pointer value (random address) to an integer instead of referencing what it points to. Easy fix.
Instead of this:
uint32_t res = reinterpret_cast<uint32_t>(content.data());
This:
uint32_t* ptr = reinterpret_cast<uint32_t*>(content.data());
uint32_t res = *ptr;
The language lawyers may take exception to the above. And because there can be issues with copying data on unaligned boundaries on some platforms. Hence, copying the 4 bytes out of content and into the address of the 32-bit integer may suffice:
memcpy(&res, content.data(), 4);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
