参考:
- http://www.codeproject.com/Articles/28681/Bitwise-Operation-Explained
- http://blog.csdn.net/haoni123321/article/details/7415498
//=============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++ 的效率果然是吊吊的。。。