与或运算和加减运算

与或加减运算

从数电位运算得角度康康加减运算,用C跑一跑


-----------------------------------------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、加法运算add:
    2+4=6;使用四位二进制表示三个数分别是:
    0010+0100=0110;
故而有:
    testnum = 2(d) = 0010(b)
    testnum+4----------------> +0100
    使用或运算符实现加法运算。也即是在对应的位(bit)上填补1

注:所谓在对应的位填补1,就是说把+2转换成把权为2的位变成1
和 对应位为1的数 作或运算 恰恰有这个功能
(和1或运算的结果恒为1)

    using xor operation ----->  0010--------->2
                               |0100--------->+4
                               -------
                                0110--------->6
    
    2、减法运算subtraction:
    testnum = 6(d) = 0110(b)
    testnum-4----------------> -0100

类比加法运算,不难得出减法运算的规律----把对应位上的数替换成0,这就要用到与运算了。和对应位位0的数相与,自然能够实现这点

    using 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值