我够大
std::vector<byte> source
Run Code Online (Sandbox Code Playgroud)
我需要从向量中的任何偏移量中获取四个字节(例如,10-13 个字节)并将其转换为整数。
int ByteVector2Int(std::vector &source, int offset)
{
return (source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24);
}
Run Code Online (Sandbox Code Playgroud)
这种方法太冒犯了,我如何才能以最大的性能做到这一点?
使用memcpy. 您可能很想使用reinterpret_cast,但是很容易以未定义的行为结束(例如由于对齐问题)。此外,通过常量引用传递向量:
int f(const std::vector<std::byte>& v, size_t n)
{
int temp;
memcpy(&temp, v.data() + n, sizeof(int));
return temp;
}
Run Code Online (Sandbox Code Playgroud)
请注意,编译器在优化方面非常出色。就我而言,GCC-O2导致:
mov rax, qword ptr [rdi]
mov eax, dword ptr [rax + rsi]
ret
Run Code Online (Sandbox Code Playgroud)
因此,没有memcpy被调用并且程序集是最小的。现场演示:https : //godbolt.org/z/oWGqej
更新(基于问题更新)
编辑后,您可能还会注意到生成的程序集与您的方法完全相同(在我的情况下):
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) );
}
Run Code Online (Sandbox Code Playgroud)
现场演示:https : //godbolt.org/z/c9dE9W
请注意,您的代码不正确。首先,执行按位操作的std::byte溢出,其次,没有隐式转换std::byteto int。
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |