以下代码将采用4位“半字节”并交换它们:

inline void swap(uint64_t& v, int pos1, int pos2) {
    pos1 <<= 2; pos2 <<= 2;
    uint64_t t1 = v & (0xFLL << pos1);
    uint64_t t2 = v & (0xFLL << pos2);
    cout << hex << t1 <<',' << t2 << '\n';
    v &= ~(t1 | t2);
    int deltaBitPos = pos1 - pos2;
    if (deltaBitPos > 0) {
        t2 <<= deltaBitPos;
        t1 >>= deltaBitPos;
    } else {
        deltaBitPos = -deltaBitPos;
        t2 >>= deltaBitPos;
        t1 <<= deltaBitPos;
    }
    v |= (t1 | t2);
}

例如:
uint64_t v = 0x123456789LL;
swap(v, 0, 1)

将导致v = 0x123456798

但是,使用某些按位原始函数有没有更快的方法呢?我找不到任何可以做到的,无论是gcc内置程序还是在bithacks上:

https://graphics.stanford.edu/~seander/bithacks.html

最佳答案

这还不错,但是我将摆脱条件并简化一下:

inline void swap(uint64_t& v, int pos1, int pos2) {
    pos1 <<= 2; pos2 <<= 2;
    uint64_t ret = v&~((0xFLL << pos1)|(0xFLL << pos2));
    ret|=((v>>pos1)&15)<<pos2;
    ret|=((v>>pos2)&15)<<pos1;
    v = ret;
}

07-24 09:28