Home > Back-end >  convert vector of 4 bytes into int c
convert vector of 4 bytes into int c

Time:03-23

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 enter image description here

it is always the same values

however the value of "res" is always changing to random numbers Can you please explain my mistake

CodePudding user response:

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);
  • Related