What is a ^ b and (a & b) << 1?2019 Community Moderator ElectionWhat is the best way to add two numbers without using the + operator?Adding two numbers without + operator (Clarification)adds two numbers without using + or any arithmetic operatorsAdding two numbers without using the addition operatorWhat is the most efficient way to deep clone an object in JavaScript?What is the !! (not not) operator in JavaScript?What is the JavaScript version of sleep()?What does “use strict” do in JavaScript, and what is the reasoning behind it?What is the “-->” operator in C++?What is the difference between call and apply?What is JSONP, and why was it created?Reference — What does this symbol mean in PHP?What are the basic rules and idioms for operator overloading?What does the C ??!??! operator do?

Is "upgrade" the right word to use in this context?

Book about superhumans hiding among normal humans

How do you talk to someone whose loved one is dying?

My adviser wants to be the first author

Problem with FindRoot

Math equation in non italic font

What are substitutions for coconut in curry?

How could an airship be repaired midflight?

World War I as a war of liberals against authoritarians?

Is it insecure to send a password in a `curl` command?

Describing a chess game in a novel

Professor being mistaken for a grad student

Tikz picture of two mathematical functions

Is there a hypothetical scenario that would make Earth uninhabitable for humans, but not for (the majority of) other animals?

How could a scammer know the apps on my phone / iTunes account?

Why did it take so long to abandon sail after steamships were demonstrated?

Is honey really a supersaturated solution? Does heating to un-crystalize redissolve it or melt it?

How well should I expect Adam to work?

Why does energy conservation give me the wrong answer in this inelastic collision problem?

Why no Iridium-level flares from other satellites?

This word with a lot of past tenses

A single argument pattern definition applies to multiple-argument patterns?

How to deal with taxi scam when on vacation?

Do I need to be arrogant to get ahead?



What is a ^ b and (a & b)



2019 Community Moderator ElectionWhat is the best way to add two numbers without using the + operator?Adding two numbers without + operator (Clarification)adds two numbers without using + or any arithmetic operatorsAdding two numbers without using the addition operatorWhat is the most efficient way to deep clone an object in JavaScript?What is the !! (not not) operator in JavaScript?What is the JavaScript version of sleep()?What does “use strict” do in JavaScript, and what is the reasoning behind it?What is the “-->” operator in C++?What is the difference between call and apply?What is JSONP, and why was it created?Reference — What does this symbol mean in PHP?What are the basic rules and idioms for operator overloading?What does the C ??!??! operator do?










16















I was doing this question in leetcode.



Request:




Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.




I can't understand the solution it gave



Could someone explain how this getSum function works?



Here is the answer in JS:






var getSum=function(a,b) 
const Sum = a^b; // I can't understand it. Please give me an example to understand it
const carry = (a & b) << 1; //I can't understand it too
if(!carry)
return Sum

return getSum(Sum,carry);
;
console.log(getSum(5,1));












share|improve this question



















  • 1





    Please edit your question to clarify what it is that you don't understand about those lines. Are you unfamiliar with what the ^, & and << operators do in JavaScript? Or are you just confused about how they can be used to calculate the sum of two numbers? "I can't understand it" is not a good question.

    – Ilmari Karonen
    4 hours ago











  • Possible duplicate of Adding two numbers without + operator (Clarification)

    – Iłya Bursov
    1 hour ago















16















I was doing this question in leetcode.



Request:




Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.




I can't understand the solution it gave



Could someone explain how this getSum function works?



Here is the answer in JS:






var getSum=function(a,b) 
const Sum = a^b; // I can't understand it. Please give me an example to understand it
const carry = (a & b) << 1; //I can't understand it too
if(!carry)
return Sum

return getSum(Sum,carry);
;
console.log(getSum(5,1));












share|improve this question



















  • 1





    Please edit your question to clarify what it is that you don't understand about those lines. Are you unfamiliar with what the ^, & and << operators do in JavaScript? Or are you just confused about how they can be used to calculate the sum of two numbers? "I can't understand it" is not a good question.

    – Ilmari Karonen
    4 hours ago











  • Possible duplicate of Adding two numbers without + operator (Clarification)

    – Iłya Bursov
    1 hour ago













16












16








16


3






I was doing this question in leetcode.



Request:




Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.




I can't understand the solution it gave



Could someone explain how this getSum function works?



Here is the answer in JS:






var getSum=function(a,b) 
const Sum = a^b; // I can't understand it. Please give me an example to understand it
const carry = (a & b) << 1; //I can't understand it too
if(!carry)
return Sum

return getSum(Sum,carry);
;
console.log(getSum(5,1));












share|improve this question
















I was doing this question in leetcode.



Request:




Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.




I can't understand the solution it gave



Could someone explain how this getSum function works?



Here is the answer in JS:






var getSum=function(a,b) 
const Sum = a^b; // I can't understand it. Please give me an example to understand it
const carry = (a & b) << 1; //I can't understand it too
if(!carry)
return Sum

return getSum(Sum,carry);
;
console.log(getSum(5,1));








var getSum=function(a,b) 
const Sum = a^b; // I can't understand it. Please give me an example to understand it
const carry = (a & b) << 1; //I can't understand it too
if(!carry)
return Sum

return getSum(Sum,carry);
;
console.log(getSum(5,1));





var getSum=function(a,b) 
const Sum = a^b; // I can't understand it. Please give me an example to understand it
const carry = (a & b) << 1; //I can't understand it too
if(!carry)
return Sum

return getSum(Sum,carry);
;
console.log(getSum(5,1));






javascript operators add






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 8 hours ago









phuclv

15.4k853229




15.4k853229










asked 21 hours ago









JackyJacky

2429




2429







  • 1





    Please edit your question to clarify what it is that you don't understand about those lines. Are you unfamiliar with what the ^, & and << operators do in JavaScript? Or are you just confused about how they can be used to calculate the sum of two numbers? "I can't understand it" is not a good question.

    – Ilmari Karonen
    4 hours ago











  • Possible duplicate of Adding two numbers without + operator (Clarification)

    – Iłya Bursov
    1 hour ago












  • 1





    Please edit your question to clarify what it is that you don't understand about those lines. Are you unfamiliar with what the ^, & and << operators do in JavaScript? Or are you just confused about how they can be used to calculate the sum of two numbers? "I can't understand it" is not a good question.

    – Ilmari Karonen
    4 hours ago











  • Possible duplicate of Adding two numbers without + operator (Clarification)

    – Iłya Bursov
    1 hour ago







1




1





Please edit your question to clarify what it is that you don't understand about those lines. Are you unfamiliar with what the ^, & and << operators do in JavaScript? Or are you just confused about how they can be used to calculate the sum of two numbers? "I can't understand it" is not a good question.

– Ilmari Karonen
4 hours ago





Please edit your question to clarify what it is that you don't understand about those lines. Are you unfamiliar with what the ^, & and << operators do in JavaScript? Or are you just confused about how they can be used to calculate the sum of two numbers? "I can't understand it" is not a good question.

– Ilmari Karonen
4 hours ago













Possible duplicate of Adding two numbers without + operator (Clarification)

– Iłya Bursov
1 hour ago





Possible duplicate of Adding two numbers without + operator (Clarification)

– Iłya Bursov
1 hour ago












3 Answers
3






active

oldest

votes


















19














Let's imagine that a = 3 and b = 5



In binary notation they are a = 0011 and b = 0101



XOR:
a^b is XOR operator. When compare two bits it returns 0 if they are same and 1 if they are different. 01^10 => 11



So when we're doing a^b result will be 0110 (6 in decimal)



AND + SHIFT



a&b performs logical AND operation. It returns 1 only when a = b = 1.



In our case the result is 0001



<< shifts it(adds 0 on the right side) and result became 0010 which sets carry variable true. (only 0000 will be false).



Next iterations:



Everything repeats but now a = 0110 and b = 0010 (Sum and carry from last execution)



Now a^b = 0100 and (a&b)<<1 = 0100



Repeating again.



Now a^b = 0000 and (a&b)<<1 = 1000



And again.



Now a^b = 1000 and (a&b)<<1 = 0000. Now carry is finally false. And we're returning 1000 which is decimal 8.



Everything worked fine since 3+5=8






share|improve this answer




















  • 1





    This only seems to discuss that particular case, not how the algorithm works in general. How are we to know from this that it works for all possible inputs?

    – ilkkachu
    2 hours ago











  • You can try any other values, it will work :)

    – flppv
    12 mins ago


















21














It's basically replicating the half-adder



Adding 2 bits A and B produces 2 outputs: a sum and a carry bit like below



╔═══════╤═════════════╗
║ Input │ Output ║
╠═══╤═══╪═══════╤═════╣
║ A │ B │ carry │ sum ║
╟───┼───┼───────┼─────╢
║ 0 │ 0 │ 0 │ 0 ║
╟───┼───┼───────┼─────╢
║ 1 │ 0 │ 0 │ 1 ║
╟───┼───┼───────┼─────╢
║ 0 │ 1 │ 0 │ 1 ║
╟───┼───┼───────┼─────╢
║ 1 │ 1 │ 1 │ 0 ║
╚═══╧═══╧═══════╧═════╝


From the table we get the logic for the outputs: carry = A and B, sum = A xor B





So the snippet above is working like this



const Sum=a^b; // sum = a xor b
const carry=(a&b)<<1; // carry = 2*(a and b), since we carry to the next bit
if(!carry)
return Sum; // no carry, so sum + carry = sum

return getSum(Sum,carry); // a + b = sum + carry


See also



  • Adding two numbers without + operator (Clarification)

  • What is the best way to add two numbers without using the + operator?

  • adds two numbers without using + or any arithmetic operators

  • Adding two numbers without using the addition operator





share|improve this answer























  • If I'm not mistaken, it would be more accurate to say it replicates full adder, because of the function's recursive call to itself - one xor plus and stage leading to another.

    – Sergiy Kolodyazhnyy
    12 hours ago











  • @SergiyKolodyazhnyy here the input has only a and b which is the half adder. The full adder capability is achieved by the recursive call which gives you a + b + 2*carry. A real full adder takes 3 inputs a + b + carryIn = sum + 2*carryOut

    – phuclv
    12 hours ago











  • Might be worth pointing out that it's a half-adder for each bit simultaneously, unlike the truth table that only shows a single bit position.

    – ilkkachu
    2 hours ago


















1














 int result = p ^ q; // XOR Operator, + without carry 0+0=0, 0+1=1+0=1, 1+1=0
int carry = (p & q) << 1; // Left Shift, 1+1=2
if (carry != 0)
return getSum(result, carry);

return result;


Start By p=5,q=6. Then the XOR would be,



0101
0110
------
0011


So, XORing results in (0011) which is actually 3 in decimal. Then ANDing p and q we get,



0101
0110
-------
0100


We get 4 (100 in binary) by ANDing 5 & 6, now if we left shift this value by 1, we get



 0100<<1=1000


So we get 8 (1000 in binary) after first recursion.As the result (carry variable) isnt zero, lets recursion again by xor value and carry value.



getSum(3, 8);


So, doing the first XORing we get,



0011
1000
-------
1011


The XORing this time yielded in 11 (1011 binary),so we perform the AND now,



0011
1000
-------
0000


We get all ZERO for ANDing 3 and 8, so this time the left shift operator also results in ZERO, as we have no 1 here which may give us a value by left shifing zeroes.
As the carry variable is now Zero, we come to the end of recursion and the XORed value will be the Sum, which is 11 (1011 in Binary).



Hope you get the working of the procedure. You can learn more by learning bitwise operation, as its the way the machine do the arithmatic operations.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55193135%2fwhat-is-a-b-and-a-b-1%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    19














    Let's imagine that a = 3 and b = 5



    In binary notation they are a = 0011 and b = 0101



    XOR:
    a^b is XOR operator. When compare two bits it returns 0 if they are same and 1 if they are different. 01^10 => 11



    So when we're doing a^b result will be 0110 (6 in decimal)



    AND + SHIFT



    a&b performs logical AND operation. It returns 1 only when a = b = 1.



    In our case the result is 0001



    << shifts it(adds 0 on the right side) and result became 0010 which sets carry variable true. (only 0000 will be false).



    Next iterations:



    Everything repeats but now a = 0110 and b = 0010 (Sum and carry from last execution)



    Now a^b = 0100 and (a&b)<<1 = 0100



    Repeating again.



    Now a^b = 0000 and (a&b)<<1 = 1000



    And again.



    Now a^b = 1000 and (a&b)<<1 = 0000. Now carry is finally false. And we're returning 1000 which is decimal 8.



    Everything worked fine since 3+5=8






    share|improve this answer




















    • 1





      This only seems to discuss that particular case, not how the algorithm works in general. How are we to know from this that it works for all possible inputs?

      – ilkkachu
      2 hours ago











    • You can try any other values, it will work :)

      – flppv
      12 mins ago















    19














    Let's imagine that a = 3 and b = 5



    In binary notation they are a = 0011 and b = 0101



    XOR:
    a^b is XOR operator. When compare two bits it returns 0 if they are same and 1 if they are different. 01^10 => 11



    So when we're doing a^b result will be 0110 (6 in decimal)



    AND + SHIFT



    a&b performs logical AND operation. It returns 1 only when a = b = 1.



    In our case the result is 0001



    << shifts it(adds 0 on the right side) and result became 0010 which sets carry variable true. (only 0000 will be false).



    Next iterations:



    Everything repeats but now a = 0110 and b = 0010 (Sum and carry from last execution)



    Now a^b = 0100 and (a&b)<<1 = 0100



    Repeating again.



    Now a^b = 0000 and (a&b)<<1 = 1000



    And again.



    Now a^b = 1000 and (a&b)<<1 = 0000. Now carry is finally false. And we're returning 1000 which is decimal 8.



    Everything worked fine since 3+5=8






    share|improve this answer




















    • 1





      This only seems to discuss that particular case, not how the algorithm works in general. How are we to know from this that it works for all possible inputs?

      – ilkkachu
      2 hours ago











    • You can try any other values, it will work :)

      – flppv
      12 mins ago













    19












    19








    19







    Let's imagine that a = 3 and b = 5



    In binary notation they are a = 0011 and b = 0101



    XOR:
    a^b is XOR operator. When compare two bits it returns 0 if they are same and 1 if they are different. 01^10 => 11



    So when we're doing a^b result will be 0110 (6 in decimal)



    AND + SHIFT



    a&b performs logical AND operation. It returns 1 only when a = b = 1.



    In our case the result is 0001



    << shifts it(adds 0 on the right side) and result became 0010 which sets carry variable true. (only 0000 will be false).



    Next iterations:



    Everything repeats but now a = 0110 and b = 0010 (Sum and carry from last execution)



    Now a^b = 0100 and (a&b)<<1 = 0100



    Repeating again.



    Now a^b = 0000 and (a&b)<<1 = 1000



    And again.



    Now a^b = 1000 and (a&b)<<1 = 0000. Now carry is finally false. And we're returning 1000 which is decimal 8.



    Everything worked fine since 3+5=8






    share|improve this answer















    Let's imagine that a = 3 and b = 5



    In binary notation they are a = 0011 and b = 0101



    XOR:
    a^b is XOR operator. When compare two bits it returns 0 if they are same and 1 if they are different. 01^10 => 11



    So when we're doing a^b result will be 0110 (6 in decimal)



    AND + SHIFT



    a&b performs logical AND operation. It returns 1 only when a = b = 1.



    In our case the result is 0001



    << shifts it(adds 0 on the right side) and result became 0010 which sets carry variable true. (only 0000 will be false).



    Next iterations:



    Everything repeats but now a = 0110 and b = 0010 (Sum and carry from last execution)



    Now a^b = 0100 and (a&b)<<1 = 0100



    Repeating again.



    Now a^b = 0000 and (a&b)<<1 = 1000



    And again.



    Now a^b = 1000 and (a&b)<<1 = 0000. Now carry is finally false. And we're returning 1000 which is decimal 8.



    Everything worked fine since 3+5=8







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 20 hours ago

























    answered 20 hours ago









    flppvflppv

    1,222725




    1,222725







    • 1





      This only seems to discuss that particular case, not how the algorithm works in general. How are we to know from this that it works for all possible inputs?

      – ilkkachu
      2 hours ago











    • You can try any other values, it will work :)

      – flppv
      12 mins ago












    • 1





      This only seems to discuss that particular case, not how the algorithm works in general. How are we to know from this that it works for all possible inputs?

      – ilkkachu
      2 hours ago











    • You can try any other values, it will work :)

      – flppv
      12 mins ago







    1




    1





    This only seems to discuss that particular case, not how the algorithm works in general. How are we to know from this that it works for all possible inputs?

    – ilkkachu
    2 hours ago





    This only seems to discuss that particular case, not how the algorithm works in general. How are we to know from this that it works for all possible inputs?

    – ilkkachu
    2 hours ago













    You can try any other values, it will work :)

    – flppv
    12 mins ago





    You can try any other values, it will work :)

    – flppv
    12 mins ago













    21














    It's basically replicating the half-adder



    Adding 2 bits A and B produces 2 outputs: a sum and a carry bit like below



    ╔═══════╤═════════════╗
    ║ Input │ Output ║
    ╠═══╤═══╪═══════╤═════╣
    ║ A │ B │ carry │ sum ║
    ╟───┼───┼───────┼─────╢
    ║ 0 │ 0 │ 0 │ 0 ║
    ╟───┼───┼───────┼─────╢
    ║ 1 │ 0 │ 0 │ 1 ║
    ╟───┼───┼───────┼─────╢
    ║ 0 │ 1 │ 0 │ 1 ║
    ╟───┼───┼───────┼─────╢
    ║ 1 │ 1 │ 1 │ 0 ║
    ╚═══╧═══╧═══════╧═════╝


    From the table we get the logic for the outputs: carry = A and B, sum = A xor B





    So the snippet above is working like this



    const Sum=a^b; // sum = a xor b
    const carry=(a&b)<<1; // carry = 2*(a and b), since we carry to the next bit
    if(!carry)
    return Sum; // no carry, so sum + carry = sum

    return getSum(Sum,carry); // a + b = sum + carry


    See also



    • Adding two numbers without + operator (Clarification)

    • What is the best way to add two numbers without using the + operator?

    • adds two numbers without using + or any arithmetic operators

    • Adding two numbers without using the addition operator





    share|improve this answer























    • If I'm not mistaken, it would be more accurate to say it replicates full adder, because of the function's recursive call to itself - one xor plus and stage leading to another.

      – Sergiy Kolodyazhnyy
      12 hours ago











    • @SergiyKolodyazhnyy here the input has only a and b which is the half adder. The full adder capability is achieved by the recursive call which gives you a + b + 2*carry. A real full adder takes 3 inputs a + b + carryIn = sum + 2*carryOut

      – phuclv
      12 hours ago











    • Might be worth pointing out that it's a half-adder for each bit simultaneously, unlike the truth table that only shows a single bit position.

      – ilkkachu
      2 hours ago















    21














    It's basically replicating the half-adder



    Adding 2 bits A and B produces 2 outputs: a sum and a carry bit like below



    ╔═══════╤═════════════╗
    ║ Input │ Output ║
    ╠═══╤═══╪═══════╤═════╣
    ║ A │ B │ carry │ sum ║
    ╟───┼───┼───────┼─────╢
    ║ 0 │ 0 │ 0 │ 0 ║
    ╟───┼───┼───────┼─────╢
    ║ 1 │ 0 │ 0 │ 1 ║
    ╟───┼───┼───────┼─────╢
    ║ 0 │ 1 │ 0 │ 1 ║
    ╟───┼───┼───────┼─────╢
    ║ 1 │ 1 │ 1 │ 0 ║
    ╚═══╧═══╧═══════╧═════╝


    From the table we get the logic for the outputs: carry = A and B, sum = A xor B





    So the snippet above is working like this



    const Sum=a^b; // sum = a xor b
    const carry=(a&b)<<1; // carry = 2*(a and b), since we carry to the next bit
    if(!carry)
    return Sum; // no carry, so sum + carry = sum

    return getSum(Sum,carry); // a + b = sum + carry


    See also



    • Adding two numbers without + operator (Clarification)

    • What is the best way to add two numbers without using the + operator?

    • adds two numbers without using + or any arithmetic operators

    • Adding two numbers without using the addition operator





    share|improve this answer























    • If I'm not mistaken, it would be more accurate to say it replicates full adder, because of the function's recursive call to itself - one xor plus and stage leading to another.

      – Sergiy Kolodyazhnyy
      12 hours ago











    • @SergiyKolodyazhnyy here the input has only a and b which is the half adder. The full adder capability is achieved by the recursive call which gives you a + b + 2*carry. A real full adder takes 3 inputs a + b + carryIn = sum + 2*carryOut

      – phuclv
      12 hours ago











    • Might be worth pointing out that it's a half-adder for each bit simultaneously, unlike the truth table that only shows a single bit position.

      – ilkkachu
      2 hours ago













    21












    21








    21







    It's basically replicating the half-adder



    Adding 2 bits A and B produces 2 outputs: a sum and a carry bit like below



    ╔═══════╤═════════════╗
    ║ Input │ Output ║
    ╠═══╤═══╪═══════╤═════╣
    ║ A │ B │ carry │ sum ║
    ╟───┼───┼───────┼─────╢
    ║ 0 │ 0 │ 0 │ 0 ║
    ╟───┼───┼───────┼─────╢
    ║ 1 │ 0 │ 0 │ 1 ║
    ╟───┼───┼───────┼─────╢
    ║ 0 │ 1 │ 0 │ 1 ║
    ╟───┼───┼───────┼─────╢
    ║ 1 │ 1 │ 1 │ 0 ║
    ╚═══╧═══╧═══════╧═════╝


    From the table we get the logic for the outputs: carry = A and B, sum = A xor B





    So the snippet above is working like this



    const Sum=a^b; // sum = a xor b
    const carry=(a&b)<<1; // carry = 2*(a and b), since we carry to the next bit
    if(!carry)
    return Sum; // no carry, so sum + carry = sum

    return getSum(Sum,carry); // a + b = sum + carry


    See also



    • Adding two numbers without + operator (Clarification)

    • What is the best way to add two numbers without using the + operator?

    • adds two numbers without using + or any arithmetic operators

    • Adding two numbers without using the addition operator





    share|improve this answer













    It's basically replicating the half-adder



    Adding 2 bits A and B produces 2 outputs: a sum and a carry bit like below



    ╔═══════╤═════════════╗
    ║ Input │ Output ║
    ╠═══╤═══╪═══════╤═════╣
    ║ A │ B │ carry │ sum ║
    ╟───┼───┼───────┼─────╢
    ║ 0 │ 0 │ 0 │ 0 ║
    ╟───┼───┼───────┼─────╢
    ║ 1 │ 0 │ 0 │ 1 ║
    ╟───┼───┼───────┼─────╢
    ║ 0 │ 1 │ 0 │ 1 ║
    ╟───┼───┼───────┼─────╢
    ║ 1 │ 1 │ 1 │ 0 ║
    ╚═══╧═══╧═══════╧═════╝


    From the table we get the logic for the outputs: carry = A and B, sum = A xor B





    So the snippet above is working like this



    const Sum=a^b; // sum = a xor b
    const carry=(a&b)<<1; // carry = 2*(a and b), since we carry to the next bit
    if(!carry)
    return Sum; // no carry, so sum + carry = sum

    return getSum(Sum,carry); // a + b = sum + carry


    See also



    • Adding two numbers without + operator (Clarification)

    • What is the best way to add two numbers without using the + operator?

    • adds two numbers without using + or any arithmetic operators

    • Adding two numbers without using the addition operator






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 19 hours ago









    phuclvphuclv

    15.4k853229




    15.4k853229












    • If I'm not mistaken, it would be more accurate to say it replicates full adder, because of the function's recursive call to itself - one xor plus and stage leading to another.

      – Sergiy Kolodyazhnyy
      12 hours ago











    • @SergiyKolodyazhnyy here the input has only a and b which is the half adder. The full adder capability is achieved by the recursive call which gives you a + b + 2*carry. A real full adder takes 3 inputs a + b + carryIn = sum + 2*carryOut

      – phuclv
      12 hours ago











    • Might be worth pointing out that it's a half-adder for each bit simultaneously, unlike the truth table that only shows a single bit position.

      – ilkkachu
      2 hours ago

















    • If I'm not mistaken, it would be more accurate to say it replicates full adder, because of the function's recursive call to itself - one xor plus and stage leading to another.

      – Sergiy Kolodyazhnyy
      12 hours ago











    • @SergiyKolodyazhnyy here the input has only a and b which is the half adder. The full adder capability is achieved by the recursive call which gives you a + b + 2*carry. A real full adder takes 3 inputs a + b + carryIn = sum + 2*carryOut

      – phuclv
      12 hours ago











    • Might be worth pointing out that it's a half-adder for each bit simultaneously, unlike the truth table that only shows a single bit position.

      – ilkkachu
      2 hours ago
















    If I'm not mistaken, it would be more accurate to say it replicates full adder, because of the function's recursive call to itself - one xor plus and stage leading to another.

    – Sergiy Kolodyazhnyy
    12 hours ago





    If I'm not mistaken, it would be more accurate to say it replicates full adder, because of the function's recursive call to itself - one xor plus and stage leading to another.

    – Sergiy Kolodyazhnyy
    12 hours ago













    @SergiyKolodyazhnyy here the input has only a and b which is the half adder. The full adder capability is achieved by the recursive call which gives you a + b + 2*carry. A real full adder takes 3 inputs a + b + carryIn = sum + 2*carryOut

    – phuclv
    12 hours ago





    @SergiyKolodyazhnyy here the input has only a and b which is the half adder. The full adder capability is achieved by the recursive call which gives you a + b + 2*carry. A real full adder takes 3 inputs a + b + carryIn = sum + 2*carryOut

    – phuclv
    12 hours ago













    Might be worth pointing out that it's a half-adder for each bit simultaneously, unlike the truth table that only shows a single bit position.

    – ilkkachu
    2 hours ago





    Might be worth pointing out that it's a half-adder for each bit simultaneously, unlike the truth table that only shows a single bit position.

    – ilkkachu
    2 hours ago











    1














     int result = p ^ q; // XOR Operator, + without carry 0+0=0, 0+1=1+0=1, 1+1=0
    int carry = (p & q) << 1; // Left Shift, 1+1=2
    if (carry != 0)
    return getSum(result, carry);

    return result;


    Start By p=5,q=6. Then the XOR would be,



    0101
    0110
    ------
    0011


    So, XORing results in (0011) which is actually 3 in decimal. Then ANDing p and q we get,



    0101
    0110
    -------
    0100


    We get 4 (100 in binary) by ANDing 5 & 6, now if we left shift this value by 1, we get



     0100<<1=1000


    So we get 8 (1000 in binary) after first recursion.As the result (carry variable) isnt zero, lets recursion again by xor value and carry value.



    getSum(3, 8);


    So, doing the first XORing we get,



    0011
    1000
    -------
    1011


    The XORing this time yielded in 11 (1011 binary),so we perform the AND now,



    0011
    1000
    -------
    0000


    We get all ZERO for ANDing 3 and 8, so this time the left shift operator also results in ZERO, as we have no 1 here which may give us a value by left shifing zeroes.
    As the carry variable is now Zero, we come to the end of recursion and the XORed value will be the Sum, which is 11 (1011 in Binary).



    Hope you get the working of the procedure. You can learn more by learning bitwise operation, as its the way the machine do the arithmatic operations.






    share|improve this answer





























      1














       int result = p ^ q; // XOR Operator, + without carry 0+0=0, 0+1=1+0=1, 1+1=0
      int carry = (p & q) << 1; // Left Shift, 1+1=2
      if (carry != 0)
      return getSum(result, carry);

      return result;


      Start By p=5,q=6. Then the XOR would be,



      0101
      0110
      ------
      0011


      So, XORing results in (0011) which is actually 3 in decimal. Then ANDing p and q we get,



      0101
      0110
      -------
      0100


      We get 4 (100 in binary) by ANDing 5 & 6, now if we left shift this value by 1, we get



       0100<<1=1000


      So we get 8 (1000 in binary) after first recursion.As the result (carry variable) isnt zero, lets recursion again by xor value and carry value.



      getSum(3, 8);


      So, doing the first XORing we get,



      0011
      1000
      -------
      1011


      The XORing this time yielded in 11 (1011 binary),so we perform the AND now,



      0011
      1000
      -------
      0000


      We get all ZERO for ANDing 3 and 8, so this time the left shift operator also results in ZERO, as we have no 1 here which may give us a value by left shifing zeroes.
      As the carry variable is now Zero, we come to the end of recursion and the XORed value will be the Sum, which is 11 (1011 in Binary).



      Hope you get the working of the procedure. You can learn more by learning bitwise operation, as its the way the machine do the arithmatic operations.






      share|improve this answer



























        1












        1








        1







         int result = p ^ q; // XOR Operator, + without carry 0+0=0, 0+1=1+0=1, 1+1=0
        int carry = (p & q) << 1; // Left Shift, 1+1=2
        if (carry != 0)
        return getSum(result, carry);

        return result;


        Start By p=5,q=6. Then the XOR would be,



        0101
        0110
        ------
        0011


        So, XORing results in (0011) which is actually 3 in decimal. Then ANDing p and q we get,



        0101
        0110
        -------
        0100


        We get 4 (100 in binary) by ANDing 5 & 6, now if we left shift this value by 1, we get



         0100<<1=1000


        So we get 8 (1000 in binary) after first recursion.As the result (carry variable) isnt zero, lets recursion again by xor value and carry value.



        getSum(3, 8);


        So, doing the first XORing we get,



        0011
        1000
        -------
        1011


        The XORing this time yielded in 11 (1011 binary),so we perform the AND now,



        0011
        1000
        -------
        0000


        We get all ZERO for ANDing 3 and 8, so this time the left shift operator also results in ZERO, as we have no 1 here which may give us a value by left shifing zeroes.
        As the carry variable is now Zero, we come to the end of recursion and the XORed value will be the Sum, which is 11 (1011 in Binary).



        Hope you get the working of the procedure. You can learn more by learning bitwise operation, as its the way the machine do the arithmatic operations.






        share|improve this answer















         int result = p ^ q; // XOR Operator, + without carry 0+0=0, 0+1=1+0=1, 1+1=0
        int carry = (p & q) << 1; // Left Shift, 1+1=2
        if (carry != 0)
        return getSum(result, carry);

        return result;


        Start By p=5,q=6. Then the XOR would be,



        0101
        0110
        ------
        0011


        So, XORing results in (0011) which is actually 3 in decimal. Then ANDing p and q we get,



        0101
        0110
        -------
        0100


        We get 4 (100 in binary) by ANDing 5 & 6, now if we left shift this value by 1, we get



         0100<<1=1000


        So we get 8 (1000 in binary) after first recursion.As the result (carry variable) isnt zero, lets recursion again by xor value and carry value.



        getSum(3, 8);


        So, doing the first XORing we get,



        0011
        1000
        -------
        1011


        The XORing this time yielded in 11 (1011 binary),so we perform the AND now,



        0011
        1000
        -------
        0000


        We get all ZERO for ANDing 3 and 8, so this time the left shift operator also results in ZERO, as we have no 1 here which may give us a value by left shifing zeroes.
        As the carry variable is now Zero, we come to the end of recursion and the XORed value will be the Sum, which is 11 (1011 in Binary).



        Hope you get the working of the procedure. You can learn more by learning bitwise operation, as its the way the machine do the arithmatic operations.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 20 hours ago

























        answered 20 hours ago









        Ayan_84Ayan_84

        520513




        520513



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55193135%2fwhat-is-a-b-and-a-b-1%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bett Inhaltsverzeichnis Geschichte | Bettformen | Bettgrößen | Andere Bezeichnungen | Bettenmangel | Betten in der bildenden Kunst | Schlafmedizinische Gesichtspunkte | Siehe auch | Literatur | Weblinks | Einzelnachweise | NavigationsmenüBett, Bettstatt, BettstelleCommons: BettBabybetten: Anwendung, Ausstattungsmerkmale und VergleichskriterienWasserbetten. Vorurteile im TestHapfnNursch10.1007/s11818-012-0584-74006250-8AKS4329276-8

            Luksemburg Sisukord Nimi | Asend | Loodus | Riigikord | Haldusjaotus | Rahvastik | Riigikaitse | Majandus | Taristu | Ajalugu | Eesti ja Luksemburgi suhted | Haridus | Kultuur | Vaata ka | Viited | Välislingid | Navigeerimismenüü50° N, 6° EÜlevaade Luksemburgi kaitsealadest.Luksemburgi rahvaarv. Statistikaamet.World Bank'i andmebaasÜlevaade Luksemburgi loodusest.Ülevaade Luksemburgi metsadest.Guy Colling. "Red List of the Vascular Plants of Luxembourg." Travaux scientifiques du Musée national d’histoire naturelle Luxembourg. 2005.Luxembourg’s biodiversity at risk.Maailma kahepaiksete andmebaas.Denis Lepage. "Luxembourg." Avibase.Ülevaade temperatuuridest. Luksemburgi meteoroloogiateenistus.Ülevaade Luksemburgist. Euroopa Liidu esinduse koduleht.Système politique. TerritoireÜlevaade Luksemburgi rahvastikust. Luksemburgi statistikaamet.Luksemburgi rahvastik. Luksemburgi statistikaamet.The World FactbookMonique Borsenberger, Paul Dickes. "Religions au Luxembourg. Quelle évolution entre 1999-2008". Luksemburgi statistikaamet. 2011.Luksemburgi peapiiskopkond. Catholic-Hierarchy.Luksemburgi armee koduleht.Luksemburgi armee relvastus.Eesti Välisministeerium.Luksemburgi rahvastik. Luksemburgi statistikaamet.Luksemburgi Eesti Seltsi koduleht.Helen Eelrand. "Raadio, mis muutis maailma." Eesti Päevaleht. 13. märts 2004.Ülevaade Luksemburgi haridussüsteemist.Ülevaade Luksemburgi keskkoolidest.Luksemburgr

            Valle di Casies Indice Geografia fisica | Origini del nome | Storia | Società | Amministrazione | Sport | Note | Bibliografia | Voci correlate | Altri progetti | Collegamenti esterni | Menu di navigazione46°46′N 12°11′E / 46.766667°N 12.183333°E46.766667; 12.183333 (Valle di Casies)46°46′N 12°11′E / 46.766667°N 12.183333°E46.766667; 12.183333 (Valle di Casies)Sito istituzionaleAstat Censimento della popolazione 2011 - Determinazione della consistenza dei tre gruppi linguistici della Provincia Autonoma di Bolzano-Alto Adige - giugno 2012Numeri e fattiValle di CasiesDato IstatTabella dei gradi/giorno dei Comuni italiani raggruppati per Regione e Provincia26 agosto 1993, n. 412Heraldry of the World: GsiesStatistiche I.StatValCasies.comWikimedia CommonsWikimedia CommonsValle di CasiesSito ufficialeValle di CasiesMM14870458910042978-6