@@ -94,16 +94,22 @@ bc_num _bc_do_add(bc_num n1, bc_num n2, size_t scale_min)
94
94
n2bytes = BC_BSWAP (n2bytes );
95
95
#endif
96
96
97
+ /*
98
+ * In order to add 1 to the "next digit" when a carry occurs, adjust it so that it
99
+ * overflows when add 10.
100
+ * e.g.
101
+ * 00001001(9) + 00000001(1) = 00001010(10) to
102
+ * 11111111 + 00000001 = 00000000(0) and carry 1
103
+ */
97
104
n1bytes += SWAR_REPEAT (0xF6 ) + n2bytes + carry ;
98
- /* If the most significant bit is 1 , a carry down has occurred. */
105
+ /* If the most significant bit is 0 , a carry has occurred. */
99
106
carry = !(n1bytes & ((BC_UINT_T ) 1 << (8 * sizeof (BC_UINT_T ) - 1 )));
100
107
101
108
/*
102
- * Check the most significant bit of each of the bytes, and if it is 1, a carry down has
103
- * occurred. When carrying down occurs, due to the difference between decimal and hexadecimal
104
- * numbers, an extra 6 is added to the lower 4 bits.
105
- * Therefore, for a byte that has been carried down, set all the upper 4 bits to 0 and subtract
106
- * 6 from the lower 4 bits to adjust it to the correct value as a decimal number.
109
+ * The calculation result is a mixture of bytes that have been carried and bytes that have not.
110
+ * The most significant bit of each byte is 0 if it is carried forward, and 1 if it is not.
111
+ * Using this, subtract the 0xF6 added for adjustment from the byte that has not been carried
112
+ * over to return it to the correct value as a decimal number.
107
113
*/
108
114
BC_UINT_T sum_mask = ((n1bytes & SWAR_REPEAT (0x80 )) >> 7 ) * 0xF6 ;
109
115
n1bytes -= sum_mask ;
0 commit comments