Home >Backend Development >C++ >Why Doesn't My C Large Precision Addition Propagate Carry Bits Correctly?
Your goal is to implement a large precision class in C , and you've encountered an issue when adding numbers together. When you add 0xffffffff and 0x04, you get 0xffff0003 instead of the expected 0x0100000003.
The highlighted section of your code is:
if (i < lhs.nbytes) { if (ret.data[i].data == 255 && ret.data[i + 1].carry == 1) increment(&trhs, i + 1); ret.data[i].data += ret.data[i + 1].carry; }
Here's why it's causing the incorrect result:
Carry Propagation: In each iteration of the loop, the carry from the previous addition should be added to the current result. However, this code only applies the carry if ret.data[i].data is 255 and ret.data[i 1].carry is 1. This means that carries are not always propagated, which results in the incorrect answer.
Incorrect Storage Order: The mpfl class seems to store numbers in little-endian format, where the least significant byte is stored in the highest index. This is not the preferred way to store numbers for addition as it makes it harder to process carries from higher-order bytes.
To resolve these issues, consider the following recommendations:
The above is the detailed content of Why Doesn't My C Large Precision Addition Propagate Carry Bits Correctly?. For more information, please follow other related articles on the PHP Chinese website!