Is this how the + operator is implemented in C?

后端 未结 9 1703
抹茶落季
抹茶落季 2021-01-30 06:21

When understanding how primitive operators such as +, -, * and / are implemented in C, I found the following snippet from an

9条回答
  •  有刺的猬
    2021-01-30 06:47

    Seems that this function demonstrates how + actually works in the background

    No. This is translated to the native add machine instruction, which is actually using the hardware adder, in the ALU.

    If you're wondering how does the computer add, here is a basic adder.

    Everything in the computer is done using logic gates, which are mostly made of transistors. The full adder has half-adders in it.

    For a basic tutorial on logic gates, and adders, see this. The video is extremely helpful, though long.

    In that video, a basic half-adder is shown. If you want a brief description, this is it:

    The half adder add's two bits given. The possible combinations are:

    • Add 0 and 0 = 0
    • Add 1 and 0 = 1
    • Add 1 and 1 = 10 (binary)

    So now how does the half adder work? Well, it is made up of three logic gates, the and, xor and the nand. The nand gives a positive current if both the inputs are negative, so that means this solves the case of 0 and 0. The xor gives a positive output one of the input is positive, and the other negative, so that means that it solves the problem of 1 and 0. The and gives a positive output only if both the inputs are positive, so that solves the problem of 1 and 1. So basically, we have now got our half-adder. But we still can only add bits.

    Now we make our full-adder. A full adder consists of calling the half-adder again and again. Now this has a carry. When we add 1 and 1, we get a carry 1. So what the full-adder does is, it takes the carry from the half-adder, stores it, and passes it as another argument to the half-adder.

    If you're confused how can you pass the carry, you basically first add the bits using the half-adder, and then add the sum and the carry. So now you've added the carry, with the two bits. So you do this again and again, till the bits you have to add are over, and then you get your result.

    Surprised? This is how it actually happens. It looks like a long process, but the computer does it in fractions of a nanosecond, or to be more specific, in half a clock cycle. Sometimes it is performed even in a single clock cycle. Basically, the computer has the ALU (a major part of the CPU), memory, buses, etc..

    If you want to learn computer hardware, from logic gates, memory and the ALU, and simulate a computer, you can see this course, from which I learnt all this: Build a Modern Computer from First Principles

    It's free if you do not want an e-certificate. The part two of the course is coming up in spring this year

提交回复
热议问题