Reputation: 55
I have big enough
std::vector<byte> source
and I need to get four bytes from any offset in vector (for example, 10-13 bytes) and convert it to integer.
int ByteVector2Int(std::vector &source, int offset)
{
return (source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24);
}
This method called too offen, how I can do that with maximum perfomance?
Upvotes: 1
Views: 1073
Reputation: 23497
Use memcpy
. You might be tempted to use reinterpret_cast
, but then you can easily end up with undefined behavior (for instance due to alignment issues). Also, pass a vector by a const reference:
int f(const std::vector<std::byte>& v, size_t n)
{
int temp;
memcpy(&temp, v.data() + n, sizeof(int));
return temp;
}
Note that compilers are very good in optimizations. In my case, GCC with -O2
resulted in:
mov rax, qword ptr [rdi]
mov eax, dword ptr [rax + rsi]
ret
So, there is no memcpy
invoked and the assembly is minimal. Live demo: https://godbolt.org/z/oWGqej
UPDATE (based on question update)
After edit, you may also notice that the generated assembly is the very same (in my case) as for your approach:
int f2(const std::vector<std::byte>& v, size_t n)
{
return (int)(
(unsigned int)v[n]
+ ((unsigned int)v[n + 1] << 8)
+ ((unsigned int)v[n + 2] << 16)
+ ((unsigned int)v[n + 3] << 24) );
}
Live demo: https://godbolt.org/z/c9dE9W
Note that your code is not correct. First, bitwise operations are performed with std::byte
which overflows, and second, there is no implicit conversion of std::byte
to int
.
Upvotes: 6