How computer do addition and subtraction

As a human being, we can do a lot of mathematic calculation in our mind. But for the computer, they like the thing to be as easy as possible. So, this chapter will talk about how the computer to the mathematic like addition and subtraction.


Question

Before we begin the topic, let's consider a question:

how to calculate the sum of two integer without using + and - ?

Note: the answer can be find in the Answer section.


Let's begin here.

We both konw that, computer just know 0 and 1. If a computer want to calculate 1+3, it will do as follow:

  1. change 1 to binary system which look like 0000 0001(let assue the computer is 8-bit in this article)
  2. change 3 to binary system, so it will be 0000 0011
  3. add this two number together, if meet 2 then carry 1 and place 0 in the original position. So, we get 0000 0100 which represent 4 in decimal system.

What's more, for a computer, the highest bit is used for storing the symbol of this number, 0 means positive and 1 means negative. This kind of representative measure called "sign and magnitude".

So, +1 will be 0000 0001 and -1 will become 1000 0001.

The addition is finished here, but how about subtraction? From math class, we know that subtraction can be seem as addition. For example:

2 - 1 = 2 + (-1)

With this idea, the computer scientists want to find a way that can use the same hardware system to deal with the subtraction just like the addition. Here is the ones' complement. Let's give the definition of this guy,

for a positive number, its one's complement is itself; for a negative number, its one's complement number is inverting all the bits in the binary representation of the number except the symbol bit.

For example,

  • +1, its one's complement is 0000 0001
  • -1, its one's complement is 1111 1110

Computer scientists say thar with the one's complement we can almost treat subtraction as addition , let's test whether it can do subtraction like addition or not. If I have a -3 and a 6, the step of the calculation should as follow:

  1. -3 ---> 1000 0011 and 6 ---> 0000 0110
  2. take their ones' complement respectively, so we get 1111 1100 and 0000 0110
  3. add them together:
 1111 1100
 0000 0110
----------
10000 0010 (overflow) = 0000 0011 = 3 (decimal)

From the steps above, the one's complement worked! But, we need to know the rule of overflow. If we get an overflow, we have to remove the highest-bit and add one to the lowest-bit.

Actually, the one's complement worked at most time, except some cases whose answer is 0. For exmaple, 1 + (-1) = 0:

 0000 0001
 1111 1110
----------
 1111 1111[ones' complement] = 1000 0000[sign and magnitude] = -0

In this case, we get a minus zero. What is -0, as human being, we treat -0 = 0. But if we need to make the computer know they are the same, it will waste some resources. The computer scientists believe that there will another way just need the computer to know zero.

Luckily, they created something called

"two's complement" to solve this problem. The definition of two's complement as follow:

for positive number, the two's complement is itself; for negative number, the two's complement is its ones' complement plus one.

Let check, can it fix the minus zeor problem. Take the same example, 1 + (-1) = 0:

 0000 0001
 1111 1111
----------
10000 0000(overflow) = 0000 0000 = 0(demical)

Unfortunately, we got an overflow again. But when we using two's complement for calculation, we do not need do to other job for the overflow, just ignore it.

That is how the computer do addition and subtraction. Every number you input in a computer, it will change it into its two's complement then do the calculation. In the way, we can know that the computer treat subtraction as addition. Only a set of hardware can finish the job.


Answer

With the knowledge above, we almost reach the answer. Of course, we need to figure out this question like a computer which mean we need to think in binary way. But please don't try to use if...else... to do the math, in that way, you need to write a lot of codes and need to separate additoin and subtraction.

Do you remember these two kinds of bit operation:

& operation
A    B     A&B
0    0      0
0    1      0
1    0      0
1    1      1
----------------
^ operation
A    B     A^B
0    0      0
0    1      1
1    0      1
1    1      0

We know the computer will treat the subtraction as the addition, so we just need to figure out the how the addition work then the subtraction will be done. For addition, we always need to check whether there is a carry or not. We notice that:

  • just consider the carry, the answer is same as & operation
  • just consider the addition(without carry), the answer is same as ^ operation

So, we can do find out where the carry is by & operation and do the addition by ^ operation.

I will implement it in java, the code as follow:

// using loop
public int GetSum(int a, int b){
    while (b != 0) {    
        int c = a & b;
        a = a ^ b;
        b = c << 1;
    }
    return a;
}

// using recursion
public int GetSum(int a, int b){
    (b != 0) ? GetSum(a ^ b, (a & b) << 1 ) : return a;
}

Sept. 28, 2016 Montreal
Eric Lai

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,802评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,109评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,683评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,458评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,452评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,505评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,901评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,550评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,763评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,556评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,629评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,330评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,898评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,897评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,140评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,807评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,339评论 2 342

推荐阅读更多精彩内容

  • 小闺蜜问我:“你觉得怎样才算真正爱过一个人?” 我说:“那必定是得刻骨铭心。” 小闺蜜笑了:“看来你经验丰富啊。”...
    橘生淮南lori阅读 850评论 11 8
  • 一个神秘的男朋友,那我就当你不存在吧!
    一抹清澄的忧伤阅读 191评论 0 0
  • 晚风拂入夕阳,他满是伤痕的手颤巍巍的抬起,捋了捋花白的胡须。拿起那对早已玉化的青皮核桃,躺在摇椅里,夕阳下安静的空...
    钟意鸯阅读 339评论 0 1
  • 作业效率比较高w 恩开学第一课真的好麻烦_(:з」∠)_ 还要背还要完成任务,学不死就死里学好嘛!! 1.预习复习...
    妮可妮可喳阅读 167评论 0 0
  • 无论多么的努力 痛苦还是一点点吞噬信心 无论多么的用心 还是无法从泥潭脱身 人生,总有一段异常的艰难 找不到出口,...
    又见依依阅读 201评论 7 8