【收集向】位操作技巧 bitwise operation trick

參考:

//=============Let`s begin================//

bitwise operation trick

交換兩數

void bitwise_swap(int& a, int& b) {
    a ^= b;
    b ^= a;
    a ^= b;
}

取反

int bitwise_sign_reverse(int& a) {
    return ~a + 1;
}

取絕對值

// version 1
int bitwise_abs(int& a) {
    return (a >> 31) ? ( ~a + 1 ) : a;
}

// version 2
int bitwise_abs(int& a) {
    int highest = a >> 31;
    return (highest & ( ~a + 1 )) | (~highest & a);
}
// version 3
int bitwise_abs(int& a) {
    int i = a >> 31;
    return ((a^i) - i);
}

是否爲2的冪

// 對 x 爲正整數有效
// version1
bool bitwise_is_power_of_two(int x) {
    return ( x & ( x - 1 ) ) == 0;
}
// version2
bool bitwise_is_power_of_two(int x) {
    return ( (x & (-x) ) == x );
}

非科學測試

本機環境 win7 64bit, 8GB ram, amd 1.90GHz, 4 core

bitwise_swap vs swap (C++11, utility)

多次測試,bitwise_swap 耗時大約爲 swap 的 2/3 多一點。

#include <iostream>
#include <cstdio>
#include <ctime>
#include <climits>
#include <utility>
using namespace std;
#define rep(i, s, t) for(int (i)=(s);(i)<=(t);++(i))

void bitwise_swap(int& a, int& b) {
    a ^= b; b ^= a; a ^= b;
}

int main() {
    float t, delta;
    t = clock();
    rep(i, 1, 10000000) {
        int x, y;
        swap(x, y);
    }
    delta = clock() - t;
    printf("%.8f seconds\n", delta / CLOCKS_PER_SEC);

    t = clock();
    rep(i, 1, 10000000) {
        int x, y;
        bitwise_swap(x, y);
    }
    delta = clock() - t;
    printf("%.8f seconds\n", delta / CLOCKS_PER_SEC);
    return 0;
}

其它

其他的手寫bitwise操作基本無法打敗C++庫函數,甚至會慢很多。
C++ 的效率果然是吊吊的。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章