我想了解以下代碼的邏輯,即用攜帶的方式添加:
#include <iostream>
使用 命名空間 std.com.cn>。
inline unsigned char add_uint64_generic(uint64_t operand1。uint64_t operand2, unsigned char carry, unsigned long long *result)
{
operand1 = operand2。
*result = operand1 carry;
return (operand1 < operand2) || (~operand1 < carry) 。
}
int main()
{
uint64_t operand1 = 10000;
uint64_t operand2 = 2000;
char carry = 255;
unsigned long long r。
std::cout << "operand1 < operand2: " << (operand1 < operand2) << std::endl;
std::cout << "(~operand1 < carry)。" << (~operand1 < carry) << std::endl;
cout<<(int) add_uint64_generic(operand1,operand2,carry,& r) << std::endl;
cout<< r。
return 0。
}
prints
operand1 < operand2: 0
(~operand1 < carry): 1 (~operand1 < carry).
0
12255 12255
如果
operand1 < operand2: 0
(~operand1 < carry): 1
(operand1 < operand2) || (~operand1 < carry)怎么會是0? 0||1 = 1。
另外,這看起來像是一些攜帶操作。~operand1在這里與進位有什么關系呢?
uj5u.com熱心網友回復:
std::cout << "(~operand1 < carry)。" << (~operand1 < carry) << std::endl;/code>
與該函式的作用不一致。 試試吧
std::cout << "(~sum < carry): " << (~(operand1 operand2) < carry) << std::endl;同樣,對于其他的比較,因為operand1實際上應該是和。
uj5u.com熱心網友回復:
這看起來像是一個任意精度加法的一部分。它需要三個輸入并回傳兩個輸出。輸入是任意精度數字的兩個匹配字(operand1和operand2)和一個來自前一個(低字)操作的進位。它回傳總和,它可能已經溢位和新的進位。
當計算總和operand1 operand2 carry時,有兩個機會使加法溢位,這對應于有關操作的兩個部分((operand1 < operand2) || (~operand1 < carry) )。
第一個加法被執行為operand1 = operand2,所以第一個檢查operand1 < operand2相當于檢查和是否小于其中一個加數 - operand1現在存盤的是和。這發生在操作溢位的情況下(在沒有溢位的情況下,兩個非負數相加不能使結果變小,但是執行溢位總是會使結果變小,因為它實際上是在x < 2^n的情況下加上x - 2^n)。第二個加法本可以用同樣的方法來檢查,但卻沒有。
第二部分的加法可以用同樣的方法來檢查。
檢查的第二部分,~operand1 < carry,而是主動地作業。訣竅是使用~operand1來計算2**64-operand1-1(記住2**64和0是同一個數字,由于模塊化運算)。當寫成0 - operand1 - 1 < carry時,這個運算式變得更容易理解,然后可以簡化為0 - operand1 <= carry。由于2**64 - operand1顯然是需要添加到operand1以實作溢位的數字,將其與carry相比應該更有意義。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/306743.html
標籤:
上一篇:<p><strong>問題背景</strong></p> <p>我試圖為每個具有<code>.param-value</c
