恰当的移位运算总是能够让代码显得很简洁、很优雅,下面,就让我们来看一下编程中使用频率比较高的一些移位运算: 本程序在VS2010编译器下运行,VS2010中,int占4个字节(32位),下面程序也只针对int型变量(常量)进行考虑。 -
-
-
-
-
-
- #include "stdafx.h"
- #include <Windows.h>
- #include <iostream>
- using namespace std;
-
- int _tmain(int argc, _TCHAR* argv[])
- {
-
- cout<<((1<<31)-1)<<endl;
-
- cout<<(1<<31)<<endl;
- cout<<"==============================\n";
-
-
- int p=12344;
- if((p&1)==1)
- {
- cout<<p<<"是奇数!"<<endl;
- }
- else
- {
- cout<<p<<"是偶数!"<<endl;
- }
- cout<<"==============================\n";
-
-
-
- int a=2,b=3;
- a=a*b;
- b=a/b;
- a=a/b;
- cout<<a<<","<<b<<endl;
- int c=4,d=5;
- c=c+d;
- d=c-d;
- c=c-d;
- cout<<c<<","<<d<<endl;
-
- int e=6,f=7;
-
-
-
-
- e^=f^=e^=f;
- cout<<e<<","<<f<<endl;
- cout<<"==============================\n";
-
-
-
-
- int h=-6;
- cout<<((h^(h>>31))-(h>>31))<<endl;
-
-
- cout<<"==============================\n";
-
-
-
- int i=2,j=3;
-
- cout<<((j&((i-j)>>31)) | (i&(~(i-j)>>31)))<<endl;
-
- cout<<((i&((i-j)>>31)) | (j&(~(i-j)>>31)))<<endl;
- cout<<"==============================\n";
-
-
-
- int k=31;
- cout<<((k&(k-1))==0)<<endl;
- cout<<"==============================\n";
-
-
-
- int m=6,n=8;
-
- cout<<((m+n)>>1)<<endl;
-
- cout<<((m^n)>>1)+(m&n)<<endl;
- cout<<"==============================\n";
-
- Sleep(5000);
- return 0;
- }
|