(Ancient heritage) chat binary operation

Long time no write data, and one is now too many things to write, to think about things too much, have no time to sit down and sort out interesting information came out (in fact, too lazy or because their own.)
Tonight happened to see Some people do not have to ask the operator how to achieve a built-+ + method, this issue reminds me without comparison operators (<,>, =) how to achieve more, in fact, is not a problem with the way I understand it to understand in fact, issue a primary school = - =.
That as I said earlier it would set up a final goal.

如何从零开始实现一个比较运算符。

(Obviously today this is not the ultimate goal of the talk, and probably will not speak up.)

首先我们先在数学上讲得通道理再拿到计算机里面看着实现,比较这事情呢,主要就看与0的结果。
比如:a > b => a - b > 0,那我们只需要知道 (a-b) 的结果的正负号就可以做出比较的结果了。
所以我们得有正负数的定义吧,然后还得有(a-b)的减法实现吧。
那么如何实现减法呢?一个正数加上一个负数是不是就有了减法呢?确实是,但是很可惜,这很多余。
实际上,你写出了加法就一定写得出减法,这是我们过去九年义务教育里面教的一种运算方式告诉我们的。

小时候,我们最早计算9+11的时候是这样算的。
     11
   +  9
-------
     20
没错吧,这个我认为中国人都应该知道的吧,这个在我这里叫竖式计算,虽然我并不确定它是不是就叫这名字,反正百度是这么说的,废话真多。
其实,这个在二进制数中也是可行的,而上面那个是十进制的,二进制的就叫逢二进一。

     11    =>        1011
   +  9    =>    +  1001
-------              --------
     20              10100
这个结果你能接受的话,那我们就进入到代码实现部分吧。
对于二进制的竖式计算中存在两个逻辑,分别是进位和合并。
进位指对列同为1的执行逢二进一,合并指对列不同数值的执行为1。
以上逻辑将分别用二进制运算来取代,前者可以视为按位与(&)和左移一位,后者可以视为两数执行按位或。
我附加一点二进制运算说明吧。

在位运算中^和&分别产生以下结果。
  1011
^ 1001
---------     
  0010

Mathematical meaning, reserved not carry results.
(The same as a carry, the same results without 0, which is to cover the final result becomes zero, it can be understood as the result of a carry.)

  1011

& 1001
---------
1001
mathematical sense to mark all the carry position, its implementation << 1 to get the results into bits.

1011 A
B 1001
according to the operational vertical seen:
1011
+ 1001
---------
00010 // Reserved bit result into the non-
10010 // results obtained carry
---------
10000 // reserved results not carry the
results obtained carry 00100 //
---------
10100 // reservations not carry the result of
the result of the carry 00000 // get
the combined results can still check for carry, not until the final into the presence bit number, then the end of the addition.

= - = I'm tired, do not want to write so be it, finally posted code.

unsigned add(unsigned a, unsigned b)
{
    unsigned sum, carry;
    while(1)
    {
        sum = a ^ b, carry = a & b;
        if(0 == carry) 
        {
            break;
        }
        a = sum, b = carry << 1;
    }
    return sum;
}
unsigned Add(unsigned a, unsigned b)
{
    unsigned sum = a ^ b, carry = a & b;
    return (0 != carry) ? Add(sum, carry << 1) : sum;
}

Guess you like

Origin www.cnblogs.com/juwan/p/11448980.html