20个位运算知多少2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
| int getMaxInt1(){
return ( 1 << 31 ) – 1; //优先级括号不能省略
}
int getMaxInt2(){
return ~( 1 << 31 );
}
int getMaxInt3(){
return ( 1 << -1 ) – 1; //gcc 不支持
}
int getMaxInt4(){
return ( (unsigned int) – 1 ) >> 1;
}
int getMinInt5(){
return 1 << 31; //获取int类型的最小值
}
int getMinInt6(){
return 1 << -1; //gcc 不支持
}
int getMaxLong(){
return ((unsigned long) – 1 ) >> 1;
}
int getMinLong(){
return 1 << 63;
}
int mulTwo(int n){
return n << 1;
}
int divTwo(int n){
return n >> 1;
}
int mulTwoPower(int n,int m){
//n*(2^m)
return n << m;
}
int divTwoPower(int n,int m){
//n/(2^m)
return n >> m;
}
bool isOddNumber(int n){
return (n & 1) == 1;
}
void swap1(int a,int b){
a ^= b;
b ^= a;
a ^= b;
cout<<a<<” “<<b<<endl;
}
void swap2(int *a,int *b){
(*a) ^= (*b) ^= (*a) ^= (*b);
}
int abs(int n){
return (n^( n >> 31 )) -( n >> 31 );
}
int main(int argc,char *argv[])
{
/*
*位运算的20则
* */
int max1 = getMaxInt1();
int max2 = getMaxInt2();
int max3 = getMaxInt4();
int min1 = getMinInt5();
int min2 = getMinInt6();
int max4 = getMaxLong();
int min3 = getMinLong();
int num1 = mulTwo(2);
int num2 = divTwo(2);
int num3 = mulTwoPower(2,1);
int num4 = divTwoPower(2,1);
int num5 = isOddNumber(4);
int num6 = isOddNumber(3);
int a=3;
int b=4;
int a1=3;
int b1=4;
a ^= b;
b ^= a;
a ^= b;
//cout<<a<<” “<<b<<endl;
//cout<<max1<<” “<<max2<<” “<<max3<<endl;
//cout<<min1<<” “<<min2<<endl;
//cout<<max4<<endl;
//cout<<min3<<endl;
//cout<<num1<<” “<<num2<<endl;
//cout<<num3<<” “<<num4<<endl;
//cout<<num5<<” “<<num6<<endl;
//swap1(a,b);
//cout<<a<<” “<<b<<endl;
//swap2(&a1,&b1);
//cout<<a1<<” “<<b1<<endl;
int abs1 = abs(-5);
cout<<abs1<<endl;
return 0;
}
|