在 C++ 中反转十六进制数的半字节(例如数字)的最快方法是什么?
以下是我的意思的示例:0x12345 -> 0x54321
这是我已经拥有的:
unsigned int rotation (unsigned int hex) {
unsigned int result = 0;
while (hex) {
result = (result << 4) | (hex & 0xF);
hex >>= 4;
}
return result;
}
最佳答案
这个问题可以分为两部分:
- 反转整数的半字节。反转字节,并交换每个字节内的半字节。
- 将反转结果右移一定量以调整“可变长度”。有
std::countl_zero(x) & -4
(前导零的数量,向下舍入为 4 的倍数)前导零位是十六进制前导零的一部分,右移该数量使它们不参与反转。
例如,使用 <bit>
中的一些新函数:
#include <stdint.h>
#include <bit>
uint32_t reverse_nibbles(uint32_t x) {
// reverse bytes
uint32_t r = std::byteswap(x);
// swap adjacent nibbles
r = ((r & 0x0F0F0F0F) << 4) | ((r >> 4) & 0x0F0F0F0F);
// adjust for variable-length of input
int len_of_zero_prefix = std::countl_zero(x) & -4;
return r >> len_of_zero_prefix;
}
这需要 C++23 std::byteswap
这可能有点乐观,你可以用其他一些字节交换来替代它。
轻松适应uint64_t
也是。
关于c++ - C++ 中十六进制数的反转半字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75264185/