c++ - C++ 中十六进制数的反转半字节

标签 c++ hex

在 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/

相关文章:

c++ - 如何使用 boost::iostreams::file_descriptor_source 读取文件?

c++ - 在 C++ 中将 long long 转换为十六进制和二进制

c - 使用原始套接字创建 IP、IGMP 数据包时,如何在这些数据包中填充十六进制值?

c - 用 c (UTF-8) 编写代码的风格

c166 引导加载程序写入内部闪存

c# - 将包含十六进制值的字节数组转换为十进制值

c++ - 我可以在成员函数内对这个指针应用删除吗?

c++ - GlobalMemoryStatusEx 线程安全吗?

c++ - 使用 Xbox 360 Controller 的鼠标模拟

python - 在 python openCV 中一次将许 multimap 像读入内存