get unsigned long long addition carryHow do I detect unsigned integer multiply overflow?Why doesn't C have unsigned floats?Improve INSERT-per-second performance of SQLite?Why are elementwise additions much faster in separate loops than in a combined loop?Printing unsigned long long int Value Type Returns Strange Resultsunsigned long int giving integer overflowEquivalent of atoi for unsigned integersC unsigned long long and imulqHow to add the former carry to the 64 bit addition using gcc asmImplicit conversion double to unsigned long overflow c++

Is it safe to keep the GPU on 100% utilization for a very long time?

Exactly which act of bravery are Luke and Han awarded a medal for?

Fuzzy vector logos from InDesign to Acrobat PDF

Wiper fluid only squirts out for a second - Hyundai Accent 2006

Light Switch Neutrals: Bundle all together?

Existence of a weight of a representation in the fundamental Weyl chamber

Are wands in any sort of book going to be too much like Harry Potter?

What are my options legally if NYC company is not paying salary?

How do I give a darkroom course without negatives from the attendees?

Should one save up to purchase a house/condo or maximize their 401k first?

Can a character shove an enemy who is already prone?

I want to write a blog post building upon someone else's paper, how can I properly cite/credit them?

Can I bring back Planetary Romance as a genre?

Colorless commander using lands that chose based upon identity?

How to start your Starctaft II games vs AI immediatly?

How can I test a shell script in a "safe environment" to avoid harm to my computer?

My Sixteen Friendly Students

Was Mohammed the most popular first name for boys born in Berlin in 2018?

Is there an application which does HTTP PUT?

How would an instant or sorcery with an effect that targets work with Feather?

get unsigned long long addition carry

What's the difference between "ricochet" and "bounce"?

What is the Ancient One's mistake?

How could a civilization detect tachyons?



get unsigned long long addition carry


How do I detect unsigned integer multiply overflow?Why doesn't C have unsigned floats?Improve INSERT-per-second performance of SQLite?Why are elementwise additions much faster in separate loops than in a combined loop?Printing unsigned long long int Value Type Returns Strange Resultsunsigned long int giving integer overflowEquivalent of atoi for unsigned integersC unsigned long long and imulqHow to add the former carry to the 64 bit addition using gcc asmImplicit conversion double to unsigned long overflow c++






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








8















I want to get the carry bit of adding two unsigned 64-bit integers in c.
I can use x86-64 asm if needed.
code:



#include <stdio.h>

typedef unsigned long long llu;

int main(void)
llu a = -1, b = -1;
int carry = /*carry of a+b*/;
llu res = a+b;
printf("a+b = %llu (because addition overflowed), carry bit = %dn", res, carry);
return 0;










share|improve this question



















  • 1





    Can you use GCC or Clang built-ins? carry = __builtin_add_overflow(a, b, &res) stores the low bits of the result in res and sets carry to if overflow occurred. (The function actually returns a bool that is true or false, so assigning it to carry will produce 1 or 0.)

    – Eric Postpischil
    4 hours ago












  • Note that msvc (if that's what you are using) also has a builtin for efficiently handling overflow (_addcarry_u64).

    – David Wohlferd
    1 hour ago

















8















I want to get the carry bit of adding two unsigned 64-bit integers in c.
I can use x86-64 asm if needed.
code:



#include <stdio.h>

typedef unsigned long long llu;

int main(void)
llu a = -1, b = -1;
int carry = /*carry of a+b*/;
llu res = a+b;
printf("a+b = %llu (because addition overflowed), carry bit = %dn", res, carry);
return 0;










share|improve this question



















  • 1





    Can you use GCC or Clang built-ins? carry = __builtin_add_overflow(a, b, &res) stores the low bits of the result in res and sets carry to if overflow occurred. (The function actually returns a bool that is true or false, so assigning it to carry will produce 1 or 0.)

    – Eric Postpischil
    4 hours ago












  • Note that msvc (if that's what you are using) also has a builtin for efficiently handling overflow (_addcarry_u64).

    – David Wohlferd
    1 hour ago













8












8








8








I want to get the carry bit of adding two unsigned 64-bit integers in c.
I can use x86-64 asm if needed.
code:



#include <stdio.h>

typedef unsigned long long llu;

int main(void)
llu a = -1, b = -1;
int carry = /*carry of a+b*/;
llu res = a+b;
printf("a+b = %llu (because addition overflowed), carry bit = %dn", res, carry);
return 0;










share|improve this question
















I want to get the carry bit of adding two unsigned 64-bit integers in c.
I can use x86-64 asm if needed.
code:



#include <stdio.h>

typedef unsigned long long llu;

int main(void)
llu a = -1, b = -1;
int carry = /*carry of a+b*/;
llu res = a+b;
printf("a+b = %llu (because addition overflowed), carry bit = %dn", res, carry);
return 0;







c x86-64 addition integer-overflow extended-precision






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 53 mins ago









Peter Cordes

138k19211354




138k19211354










asked 4 hours ago









neo5003neo5003

441




441







  • 1





    Can you use GCC or Clang built-ins? carry = __builtin_add_overflow(a, b, &res) stores the low bits of the result in res and sets carry to if overflow occurred. (The function actually returns a bool that is true or false, so assigning it to carry will produce 1 or 0.)

    – Eric Postpischil
    4 hours ago












  • Note that msvc (if that's what you are using) also has a builtin for efficiently handling overflow (_addcarry_u64).

    – David Wohlferd
    1 hour ago












  • 1





    Can you use GCC or Clang built-ins? carry = __builtin_add_overflow(a, b, &res) stores the low bits of the result in res and sets carry to if overflow occurred. (The function actually returns a bool that is true or false, so assigning it to carry will produce 1 or 0.)

    – Eric Postpischil
    4 hours ago












  • Note that msvc (if that's what you are using) also has a builtin for efficiently handling overflow (_addcarry_u64).

    – David Wohlferd
    1 hour ago







1




1





Can you use GCC or Clang built-ins? carry = __builtin_add_overflow(a, b, &res) stores the low bits of the result in res and sets carry to if overflow occurred. (The function actually returns a bool that is true or false, so assigning it to carry will produce 1 or 0.)

– Eric Postpischil
4 hours ago






Can you use GCC or Clang built-ins? carry = __builtin_add_overflow(a, b, &res) stores the low bits of the result in res and sets carry to if overflow occurred. (The function actually returns a bool that is true or false, so assigning it to carry will produce 1 or 0.)

– Eric Postpischil
4 hours ago














Note that msvc (if that's what you are using) also has a builtin for efficiently handling overflow (_addcarry_u64).

– David Wohlferd
1 hour ago





Note that msvc (if that's what you are using) also has a builtin for efficiently handling overflow (_addcarry_u64).

– David Wohlferd
1 hour ago












2 Answers
2






active

oldest

votes


















5














Carry can be only 0 or 1. 1 if there was a wrapping-around and 0 otherwise.
The wrapping-around is happening in case a + b > ULONG_LONG_MAX is true . Note, this is in mathematical terms, not in terms of C, as if a + b is actually overflowing, then this will not work. Instead you want to rearrange it to be a > ULONG_LONG_MAX - b. So the value of carry will be:



carry = a > ULONG_LONG_MAX - b ? 1 : 0;


or any preferred style equivalent.



  • Don't forget to include limits.h.





share|improve this answer























  • The ? 1 : 0 is superfluous.

    – jxh
    4 hours ago











  • @jxh This is depending on the style dictated by the house rules.

    – Eugene Sh.
    4 hours ago











  • @EugeneSh. What do you mean?

    – Broman
    4 hours ago











  • @Broman By what? Some style guides tell to explicitly state the integer values resulting from conditional. Some may even require to have an if/else construct here. You are free to pick one.

    – Eugene Sh.
    4 hours ago











  • @EugeneSh. I get it. Thanks.

    – Broman
    4 hours ago


















5














As @EugeneSh. observes, the carry is either 0 or 1. Moreover, given that a and b both have the same unsigned type, their sum is well defined even if the arithmetic result exceeds the range of their type. Moreover, the (C) result of the sum will be less than both a and b when overflow occurs, and greater otherwise, so we can use the fact that C relational operations evaluate to either 0 or 1 to express the carry bit as



carry = (a + b) < a;


That does not require any headers, nor does it depend on a specific upper bound, or even on a and b having the same type. As long as both have unsigned types, it reports correctly on whether the sum overflows the wider of their types or unsigned int (whichever is wider), which is the same as their sum setting the carry bit. As a bonus, it is expressed in terms of the sum itself, which I think makes it clear what's being tested.






share|improve this answer

























  • thanks /*complete thanks message*/

    – neo5003
    4 hours ago











  • @neo5003: you can mark an answer as accepted using the checkmark under the vote arrows.

    – Peter Cordes
    1 hour ago






  • 1





    Warning: extending this to carry_out = (a + b + carry_in) < a doesn't work, because for example b = 0xFFFF... and carry_in = 1 has already produced a carry that you won't detect with a + 0 < a being false. But yes, for add with carry-out but not carry-in, this works great. And modern compilers often can optimize c+d + carry into an adc instruction. You only run into big problems getting compilers to emit a chain of add/adc/adc/adc where you need to use the carry-out from an adc, not add.

    – Peter Cordes
    56 mins ago












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%2f56027411%2fget-unsigned-long-long-addition-carry%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









5














Carry can be only 0 or 1. 1 if there was a wrapping-around and 0 otherwise.
The wrapping-around is happening in case a + b > ULONG_LONG_MAX is true . Note, this is in mathematical terms, not in terms of C, as if a + b is actually overflowing, then this will not work. Instead you want to rearrange it to be a > ULONG_LONG_MAX - b. So the value of carry will be:



carry = a > ULONG_LONG_MAX - b ? 1 : 0;


or any preferred style equivalent.



  • Don't forget to include limits.h.





share|improve this answer























  • The ? 1 : 0 is superfluous.

    – jxh
    4 hours ago











  • @jxh This is depending on the style dictated by the house rules.

    – Eugene Sh.
    4 hours ago











  • @EugeneSh. What do you mean?

    – Broman
    4 hours ago











  • @Broman By what? Some style guides tell to explicitly state the integer values resulting from conditional. Some may even require to have an if/else construct here. You are free to pick one.

    – Eugene Sh.
    4 hours ago











  • @EugeneSh. I get it. Thanks.

    – Broman
    4 hours ago















5














Carry can be only 0 or 1. 1 if there was a wrapping-around and 0 otherwise.
The wrapping-around is happening in case a + b > ULONG_LONG_MAX is true . Note, this is in mathematical terms, not in terms of C, as if a + b is actually overflowing, then this will not work. Instead you want to rearrange it to be a > ULONG_LONG_MAX - b. So the value of carry will be:



carry = a > ULONG_LONG_MAX - b ? 1 : 0;


or any preferred style equivalent.



  • Don't forget to include limits.h.





share|improve this answer























  • The ? 1 : 0 is superfluous.

    – jxh
    4 hours ago











  • @jxh This is depending on the style dictated by the house rules.

    – Eugene Sh.
    4 hours ago











  • @EugeneSh. What do you mean?

    – Broman
    4 hours ago











  • @Broman By what? Some style guides tell to explicitly state the integer values resulting from conditional. Some may even require to have an if/else construct here. You are free to pick one.

    – Eugene Sh.
    4 hours ago











  • @EugeneSh. I get it. Thanks.

    – Broman
    4 hours ago













5












5








5







Carry can be only 0 or 1. 1 if there was a wrapping-around and 0 otherwise.
The wrapping-around is happening in case a + b > ULONG_LONG_MAX is true . Note, this is in mathematical terms, not in terms of C, as if a + b is actually overflowing, then this will not work. Instead you want to rearrange it to be a > ULONG_LONG_MAX - b. So the value of carry will be:



carry = a > ULONG_LONG_MAX - b ? 1 : 0;


or any preferred style equivalent.



  • Don't forget to include limits.h.





share|improve this answer













Carry can be only 0 or 1. 1 if there was a wrapping-around and 0 otherwise.
The wrapping-around is happening in case a + b > ULONG_LONG_MAX is true . Note, this is in mathematical terms, not in terms of C, as if a + b is actually overflowing, then this will not work. Instead you want to rearrange it to be a > ULONG_LONG_MAX - b. So the value of carry will be:



carry = a > ULONG_LONG_MAX - b ? 1 : 0;


or any preferred style equivalent.



  • Don't forget to include limits.h.






share|improve this answer












share|improve this answer



share|improve this answer










answered 4 hours ago









Eugene Sh.Eugene Sh.

12.6k22342




12.6k22342












  • The ? 1 : 0 is superfluous.

    – jxh
    4 hours ago











  • @jxh This is depending on the style dictated by the house rules.

    – Eugene Sh.
    4 hours ago











  • @EugeneSh. What do you mean?

    – Broman
    4 hours ago











  • @Broman By what? Some style guides tell to explicitly state the integer values resulting from conditional. Some may even require to have an if/else construct here. You are free to pick one.

    – Eugene Sh.
    4 hours ago











  • @EugeneSh. I get it. Thanks.

    – Broman
    4 hours ago

















  • The ? 1 : 0 is superfluous.

    – jxh
    4 hours ago











  • @jxh This is depending on the style dictated by the house rules.

    – Eugene Sh.
    4 hours ago











  • @EugeneSh. What do you mean?

    – Broman
    4 hours ago











  • @Broman By what? Some style guides tell to explicitly state the integer values resulting from conditional. Some may even require to have an if/else construct here. You are free to pick one.

    – Eugene Sh.
    4 hours ago











  • @EugeneSh. I get it. Thanks.

    – Broman
    4 hours ago
















The ? 1 : 0 is superfluous.

– jxh
4 hours ago





The ? 1 : 0 is superfluous.

– jxh
4 hours ago













@jxh This is depending on the style dictated by the house rules.

– Eugene Sh.
4 hours ago





@jxh This is depending on the style dictated by the house rules.

– Eugene Sh.
4 hours ago













@EugeneSh. What do you mean?

– Broman
4 hours ago





@EugeneSh. What do you mean?

– Broman
4 hours ago













@Broman By what? Some style guides tell to explicitly state the integer values resulting from conditional. Some may even require to have an if/else construct here. You are free to pick one.

– Eugene Sh.
4 hours ago





@Broman By what? Some style guides tell to explicitly state the integer values resulting from conditional. Some may even require to have an if/else construct here. You are free to pick one.

– Eugene Sh.
4 hours ago













@EugeneSh. I get it. Thanks.

– Broman
4 hours ago





@EugeneSh. I get it. Thanks.

– Broman
4 hours ago













5














As @EugeneSh. observes, the carry is either 0 or 1. Moreover, given that a and b both have the same unsigned type, their sum is well defined even if the arithmetic result exceeds the range of their type. Moreover, the (C) result of the sum will be less than both a and b when overflow occurs, and greater otherwise, so we can use the fact that C relational operations evaluate to either 0 or 1 to express the carry bit as



carry = (a + b) < a;


That does not require any headers, nor does it depend on a specific upper bound, or even on a and b having the same type. As long as both have unsigned types, it reports correctly on whether the sum overflows the wider of their types or unsigned int (whichever is wider), which is the same as their sum setting the carry bit. As a bonus, it is expressed in terms of the sum itself, which I think makes it clear what's being tested.






share|improve this answer

























  • thanks /*complete thanks message*/

    – neo5003
    4 hours ago











  • @neo5003: you can mark an answer as accepted using the checkmark under the vote arrows.

    – Peter Cordes
    1 hour ago






  • 1





    Warning: extending this to carry_out = (a + b + carry_in) < a doesn't work, because for example b = 0xFFFF... and carry_in = 1 has already produced a carry that you won't detect with a + 0 < a being false. But yes, for add with carry-out but not carry-in, this works great. And modern compilers often can optimize c+d + carry into an adc instruction. You only run into big problems getting compilers to emit a chain of add/adc/adc/adc where you need to use the carry-out from an adc, not add.

    – Peter Cordes
    56 mins ago
















5














As @EugeneSh. observes, the carry is either 0 or 1. Moreover, given that a and b both have the same unsigned type, their sum is well defined even if the arithmetic result exceeds the range of their type. Moreover, the (C) result of the sum will be less than both a and b when overflow occurs, and greater otherwise, so we can use the fact that C relational operations evaluate to either 0 or 1 to express the carry bit as



carry = (a + b) < a;


That does not require any headers, nor does it depend on a specific upper bound, or even on a and b having the same type. As long as both have unsigned types, it reports correctly on whether the sum overflows the wider of their types or unsigned int (whichever is wider), which is the same as their sum setting the carry bit. As a bonus, it is expressed in terms of the sum itself, which I think makes it clear what's being tested.






share|improve this answer

























  • thanks /*complete thanks message*/

    – neo5003
    4 hours ago











  • @neo5003: you can mark an answer as accepted using the checkmark under the vote arrows.

    – Peter Cordes
    1 hour ago






  • 1





    Warning: extending this to carry_out = (a + b + carry_in) < a doesn't work, because for example b = 0xFFFF... and carry_in = 1 has already produced a carry that you won't detect with a + 0 < a being false. But yes, for add with carry-out but not carry-in, this works great. And modern compilers often can optimize c+d + carry into an adc instruction. You only run into big problems getting compilers to emit a chain of add/adc/adc/adc where you need to use the carry-out from an adc, not add.

    – Peter Cordes
    56 mins ago














5












5








5







As @EugeneSh. observes, the carry is either 0 or 1. Moreover, given that a and b both have the same unsigned type, their sum is well defined even if the arithmetic result exceeds the range of their type. Moreover, the (C) result of the sum will be less than both a and b when overflow occurs, and greater otherwise, so we can use the fact that C relational operations evaluate to either 0 or 1 to express the carry bit as



carry = (a + b) < a;


That does not require any headers, nor does it depend on a specific upper bound, or even on a and b having the same type. As long as both have unsigned types, it reports correctly on whether the sum overflows the wider of their types or unsigned int (whichever is wider), which is the same as their sum setting the carry bit. As a bonus, it is expressed in terms of the sum itself, which I think makes it clear what's being tested.






share|improve this answer















As @EugeneSh. observes, the carry is either 0 or 1. Moreover, given that a and b both have the same unsigned type, their sum is well defined even if the arithmetic result exceeds the range of their type. Moreover, the (C) result of the sum will be less than both a and b when overflow occurs, and greater otherwise, so we can use the fact that C relational operations evaluate to either 0 or 1 to express the carry bit as



carry = (a + b) < a;


That does not require any headers, nor does it depend on a specific upper bound, or even on a and b having the same type. As long as both have unsigned types, it reports correctly on whether the sum overflows the wider of their types or unsigned int (whichever is wider), which is the same as their sum setting the carry bit. As a bonus, it is expressed in terms of the sum itself, which I think makes it clear what's being tested.







share|improve this answer














share|improve this answer



share|improve this answer








edited 4 hours ago

























answered 4 hours ago









John BollingerJohn Bollinger

87.6k74381




87.6k74381












  • thanks /*complete thanks message*/

    – neo5003
    4 hours ago











  • @neo5003: you can mark an answer as accepted using the checkmark under the vote arrows.

    – Peter Cordes
    1 hour ago






  • 1





    Warning: extending this to carry_out = (a + b + carry_in) < a doesn't work, because for example b = 0xFFFF... and carry_in = 1 has already produced a carry that you won't detect with a + 0 < a being false. But yes, for add with carry-out but not carry-in, this works great. And modern compilers often can optimize c+d + carry into an adc instruction. You only run into big problems getting compilers to emit a chain of add/adc/adc/adc where you need to use the carry-out from an adc, not add.

    – Peter Cordes
    56 mins ago


















  • thanks /*complete thanks message*/

    – neo5003
    4 hours ago











  • @neo5003: you can mark an answer as accepted using the checkmark under the vote arrows.

    – Peter Cordes
    1 hour ago






  • 1





    Warning: extending this to carry_out = (a + b + carry_in) < a doesn't work, because for example b = 0xFFFF... and carry_in = 1 has already produced a carry that you won't detect with a + 0 < a being false. But yes, for add with carry-out but not carry-in, this works great. And modern compilers often can optimize c+d + carry into an adc instruction. You only run into big problems getting compilers to emit a chain of add/adc/adc/adc where you need to use the carry-out from an adc, not add.

    – Peter Cordes
    56 mins ago

















thanks /*complete thanks message*/

– neo5003
4 hours ago





thanks /*complete thanks message*/

– neo5003
4 hours ago













@neo5003: you can mark an answer as accepted using the checkmark under the vote arrows.

– Peter Cordes
1 hour ago





@neo5003: you can mark an answer as accepted using the checkmark under the vote arrows.

– Peter Cordes
1 hour ago




1




1





Warning: extending this to carry_out = (a + b + carry_in) < a doesn't work, because for example b = 0xFFFF... and carry_in = 1 has already produced a carry that you won't detect with a + 0 < a being false. But yes, for add with carry-out but not carry-in, this works great. And modern compilers often can optimize c+d + carry into an adc instruction. You only run into big problems getting compilers to emit a chain of add/adc/adc/adc where you need to use the carry-out from an adc, not add.

– Peter Cordes
56 mins ago






Warning: extending this to carry_out = (a + b + carry_in) < a doesn't work, because for example b = 0xFFFF... and carry_in = 1 has already produced a carry that you won't detect with a + 0 < a being false. But yes, for add with carry-out but not carry-in, this works great. And modern compilers often can optimize c+d + carry into an adc instruction. You only run into big problems getting compilers to emit a chain of add/adc/adc/adc where you need to use the carry-out from an adc, not add.

– Peter Cordes
56 mins ago


















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%2f56027411%2fget-unsigned-long-long-addition-carry%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

Siegen Nawigatsjuun

Log på Navigationsmenu

Log på Navigationsmenu