单词内高速交换4位

时间:2015-11-20 05:03:59

标签: c++ bit-manipulation

以下代码将采用4位" nibbles"并交换它们:

$('.button').click(function(){
    var liEle = $('#addNotification').find("li:eq(0)").clone();
    $('#addNotification').append(liEle);
});

例如:

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);
}

将导致v = 0x123456798

但有一些按位原始函数有更快的方法吗?我无法找到任何可以做到的,无论是gcc内置还是bithacks:

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

1 个答案:

答案 0 :(得分:4)

它还不错,但我会摆脱条件并简化一下:

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;
}