Can't Make Value Propagate Through Carry
In a recent attempt to create a large precision mpfl class in C , the developer encountered an issue where adding 0xffffffff and 0x04 resulted in 0xffff0003 instead of the expected 0x0100000003. The add function responsible for the operation is outlined below:
mpfl operator+(const mpfl &lhs, const mpfl &rhs) { unsigned long i; mpfl ret(0); mpfl trhs(rhs); for (i = lhs.nbytes; i >= 0; i--) { if ( (unsigned short)lhs.data[i].data + (unsigned short)trhs.data[i].data > (unsigned short)255 ) { if (i > 0) { ret.data[i].carry = 1; ret.data[0].carry = 0; } else { ret.data[0].carry = 1; } } else ret.data[i].carry = 0; ret.data[i].data = lhs.data[i].data + trhs.data[i].data; 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; } if (i == 0) break; } return ret; }
While the goal of this function is to add two large precision values, it fails to handle carry propagation correctly, leading to inaccurate results. To address this issue, consider the following suggestions:
In addition, for large precision multiplication and division operations without assembly, refer to the following link for a pure C/C implementation:
[Building a Logarithm Function in C Without Using Float Type](https://stackoverflow.com/questions/11762232/building-a-logarithm-function-in-c-without-using-float-type)
The above is the detailed content of Why Does This C Large Precision Addition Function Fail to Propagate Carry Correctly?. For more information, please follow other related articles on the PHP Chinese website!