写在前面:
整理出来的一些能显著提高性能的位运算优化方法
C++
(类似)x=x*10 | x=(x<<1)+(x<<3) |
x/=2 | x>>=1 |
x%2==1 | x&1 |
x%2==0 | !(x&1) |
(long long)int a,b,c; c=a;a=b;b=c; | (long long)int a,b; a^=b;b^=a;a^=b |
x*=2n | x<<=n |
x/=2n | x>>=n |
int a; if(a<0) a=-a; | int a; a=(a^(a>>31))-(a>>31); |
long long int a; if(a<0) a=-a; | long long int a; a=(a^(a>>63))-(a>>63); |
\(取得int的最大值) | (1<<31)-1 |
\(取得long long int的最大值) | (1<<63)-1 |
\(取得int的最小值) | 1<<31 |
\(取得long long int的最小值) | 1<<63 |
(long long)int a,b; (a+b)/2; | (long long)int a,b; ((a^b)>>1)+(a&b); |
Java
(类似)x=x*10 | x=(x<<1)+(x<<3) |
x/=2 | x>>=1 |
(long long)int a,b,c; c=a;a=b;b=c; | (long long)int a,b; a^=b;b^=a;a^=b |
x*=2n | x<<=n |
x/=2n | x>>=n |
int a; if(a<0) a=-a; | int a; a=(a^(a>>31))-(a>>31); |
long long int a; if(a<0) a=-a; | long long int a; a=(a^(a>>63))-(a>>63); |
\(取得int的最大值) | (1<<31)-1 |
\(取得long long int的最大值) | (1<<63)-1 |
\(取得int的最小值) | 1<<31 |
\(取得long long int的最小值) | 1<<63 |
(long long)int a,b; (a+b)/2; | (long long)int a,b; ((a^b)>>1)+(a&b); |
(需要注意的是,Java的一大特点是取消了程序员直接操作指针)