与或加减运算
从数电位运算得角度康康加减运算,用C跑一跑
复制代码
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-----------------------------------------operation.cpp /* to understand the connection between (and、or) and (addition、subtraction) */ #include<iostream> using namespace std; int main() { int testnum(0); /* back from test for testnum */ again: /* get the integer for test */ cout<<"#please input a positive integer:#"<<endl; cin>>testnum; /* ensure the input is right */ if(testnum<0){ cout<<"wrong input"<<endl; goto again; } /* add 64 to test num by xor operation(|) */ testnum = testnum|0x40; cout<<"#testnumber + 64(|0x40)#t"<<testnum<<endl; /* substaction 64 by xand operation */ testnum = testnum&0x40; cout<<"#testnumber - 64(&0x40)#t"<<testnum<<endl; } -----------------------------------------operation.cpp
复制代码
1
2
3
4
5
6
7
8
9
10
11说明: 使用与(&)或(|)两种位运算符,分别实现正整数的减加运算 1、加法运算add: 2+4=6;使用四位二进制表示三个数分别是: 0010+0100=0110; 故而有: testnum = 2(d) = 0010(b) testnum+4----------------> +0100 使用或运算符实现加法运算。也即是在对应的位(bit)上填补1
注:所谓在对应的位填补1,就是说把+2转换成把权为2的位变成1
和 对应位为1的数 作或运算 恰恰有这个功能
(和1或运算的结果恒为1)
复制代码
1
2
3
4
5
6
7
8
9using xor operation -----> 0010--------->2 |0100--------->+4 ------- 0110--------->6 2、减法运算subtraction: testnum = 6(d) = 0110(b) testnum-4----------------> -0100
类比加法运算,不难得出减法运算的规律----把对应位上的数替换成0,这就要用到与运算了。和对应位位0的数相与,自然能够实现这点
复制代码
1
2
3
4
5
6
7
8
9using and operation to cut the '1' on right bit then,we need use ('0') and (and operation) negative code of 0100-----> 1011 --------------------------> 0110--------->6 &1011--------->-4 ------ 0010--------->2
最后
以上就是怕黑红牛最近收集整理的关于与或运算和加减运算的全部内容,更多相关与或运算和加减运算内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复