C++:从 vector<byte> 的任意位置获取 int
C++: get int from any place of vector<byte>
我够大
std::vector<byte> source
并且我需要从向量中的任何偏移量(例如,10-13 字节)中获取四个字节并将其转换为整数。
int ByteVector2Int(std::vector &source, int offset)
{
return (source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24);
}
这个方法调用的太过分了,我怎样才能以最大的性能做到这一点?
使用memcpy
。您可能会想使用 reinterpret_cast
,但是您很容易以未定义的行为结束(例如由于对齐问题)。此外,通过 const 引用传递向量:
int f(const std::vector<std::byte>& v, size_t n)
{
int temp;
memcpy(&temp, v.data() + n, sizeof(int));
return temp;
}
请注意,编译器在优化方面非常出色。就我而言,具有 -O2
的 GCC 导致:
mov rax, qword ptr [rdi]
mov eax, dword ptr [rax + rsi]
ret
因此,没有 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) );
}
现场演示:https://godbolt.org/z/c9dE9W
请注意,您的代码不正确。首先,按位运算是用 std::byte
进行溢出的,其次,没有从 std::byte
到 int
.
的隐式转换
我够大
std::vector<byte> source
并且我需要从向量中的任何偏移量(例如,10-13 字节)中获取四个字节并将其转换为整数。
int ByteVector2Int(std::vector &source, int offset)
{
return (source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24);
}
这个方法调用的太过分了,我怎样才能以最大的性能做到这一点?
使用memcpy
。您可能会想使用 reinterpret_cast
,但是您很容易以未定义的行为结束(例如由于对齐问题)。此外,通过 const 引用传递向量:
int f(const std::vector<std::byte>& v, size_t n)
{
int temp;
memcpy(&temp, v.data() + n, sizeof(int));
return temp;
}
请注意,编译器在优化方面非常出色。就我而言,具有 -O2
的 GCC 导致:
mov rax, qword ptr [rdi]
mov eax, dword ptr [rax + rsi]
ret
因此,没有 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) );
}
现场演示:https://godbolt.org/z/c9dE9W
请注意,您的代码不正确。首先,按位运算是用 std::byte
进行溢出的,其次,没有从 std::byte
到 int
.