簡體   English   中英

有沒有辦法將低 64 位乘法 int64_t * int64_t 存儲在 C 中?

[英]Is there a way to store lower 64 bits of multiplication int64_t * int64_t in C?

這是我需要使用 C 實現的 function。 請注意,不允許使用 gcc 內置函數。 感謝您的任何幫助!

'''

imull(int64_t a, int64_t b, int64_t *res) {
    // a * b = ..32bits..|..32bits..
    //                       *res
    *res = a * b;
}

'''

int64_t乘以int64_t時,真正的算術結果是一個 128 位數字,其符號位位於第 127 位。低 64 位不包含符號位。 因此,乘法的低 64 位應該在uint64_t中返回,而不是在int64_t中,這可以通過以下方式完成:

imull(int64_t a, int64_t b, uint64_t *res)
{
    *res = (uint64_t) a * (uint64_t) b;
}

(強制轉換避免了乘法中的溢出,因為無符號 integer 算術被定義為換行,而不是溢出。)

如果必須在int64_t中返回位,則可以使用 C 標准定義的方式來完成:

imull(int64_t a, int64_t b, int64_t *res)
{
    uint64_t temporary = (uint64_t) a * (uint64_t) b;
    memcpy(res, &temporary, sizeof *res);
}

memcpy<string.h>中聲明。)

另請注意,如果真正的算術結果適合int64_t ,則上述代碼返回的int64_t將等於真正的算術結果。 (這是int64_t使用的二進制補碼表示的屬性。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM