【收集向】位操作技巧 bitwise operation trick
来源:互联网 发布:centos 7 gcc 安装包 编辑:程序博客网 时间:2024/06/05 21:10
参考:
- 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 1int bitwise_abs(int& a) { return (a >> 31) ? ( ~a + 1 ) : a;}// version 2int bitwise_abs(int& a) { int highest = a >> 31; return (highest & ( ~a + 1 )) | (~highest & a);}// version 3int bitwise_abs(int& a) { int i = a >> 31; return ((a^i) - i);}
是否为2的幂
// 对 x 为正整数有效// version1bool bitwise_is_power_of_two(int x) { return ( x & ( x - 1 ) ) == 0;}// version2bool 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++ 的效率果然是吊吊的。。。
0 0
- 【收集向】位操作技巧 bitwise operation trick
- 神奇的位运算(bitwise trick)
- Bitwise Operation
- 位操作符(bitwise operator)
- 【位操作】Bitwise AND of Numbers Range
- Bitwise Operation Explained
- Bitwise Operation Explained
- Bitwise Operation及用处
- Bitwise operation and usage
- Bitwise gems - fast integer math(AS3中的位操作)
- poj 2443 Set Operation (位操作)
- Python:文件操作技巧(File operation)
- Python:文件操作技巧(File operation)
- Python:文件操作技巧(File operation)
- Python:文件操作技巧(File operation)
- Python:文件操作技巧(File operation)
- Python:文件操作技巧(File operation)
- 位操作技巧大全
- 使用Git上传本地项目文件带代码托管平台
- Reservoir Computing简介
- Android ImageView配置android:layout_height="wrap_content"时上下会有padding存在
- jQueryMobile的组件——复选框(checkbox)和单选钮(radio)
- 用GDB调试程序
- 【收集向】位操作技巧 bitwise operation trick
- C++构造函数小结
- 使用FFMPEG SDK解码流数据
- 【c++学习笔记】进入c++
- Android UI设计——Gallery控件
- 面试题29数组中出现次数超过一半的数字
- 一些做大脑研究和仿脑应用的公司
- android studio 多渠道打包,调试正式包,build.gradle解析
- 很开心假如csdn大家庭、小弟是SEO、来这是学更多的IT技术