In assembly languages, there is usually an instruction that adds two operands and a carry. If you want to implement big integer additions, you simply add the lowest integers without a carry and the next integers with a carry. How would I do that efficiently in C or C++ where I don’t have access to the carry flag? It should work on several compilers and architectures, so I cannot simply use inline assembly or such.
In assembly languages, there is usually an instruction that adds two operands and a
Share
You can use “nails” (a term from GMP): rather than using all 64 bits of a
uint64_twhen representing a number, use only 63 of them, with the top bit zero. That way you can detect overflow with a simple bit-shift. You may even want less than 63.Or, you can do half-word arithmetic. If you can do 64-bit arithmetic, represent your number as an array of
uint32_ts (or equivalently, split 64-bit words into upper and lower 32-bit chunks). Then, when doing arithmetic operations on these 32-bit integers, you can first promote to 64 bits do the arithmetic there, then convert back. This lets you detect carry, and it’s also good for multiplication if you don’t have a “multiply hi” instruction.As the other answer indicates, you can detect overflow in an unsigned addition by:
As an aside, while in practice this will also work in signed arithmetic, you have two issues:
so you’re usually better off sticking to unsigned numbers.