簡體   English   中英

模運算前如何鍵入uint32數組的強制轉換元素?

[英]How to type cast elements of uint32 array before modulo operation?

我被迫將輸出存儲在一個unsigned int數組中。 但是,輸出是對 2147483647數組中先前元素的線性組合(即 2 ^ 31-1)的線性組合的解。

下面是一個較大功能的代碼片段。 很快,當ii環繞xx的索引時,此代碼片段將產生錯誤的答案。 (請注意,在調用函數之前先xx ,以便數組中的任何元素都不為空。)

#include <stdint.h>
typedef unsigned int uint32;
typedef unit_least64_t uint64;
static uint32 xx[47];

...

xx[ii] = 12345 * (uint64)(xx[i0] + xx[ii]) % 2147483647;  // i0, ii are defined elsewhere

但是,如果將最后一行與以下內容交換,我們將不斷獲得正確的解決方案。

xx[ii] = 12345 * ( (uint64)xx[i0] + (uint64)xx[ii] ) % 2147483647;

也許,這很明顯,但是為什么有必要對unit64進行兩次類型轉換而不是一次?

只要將其放在正確的位置,一種類型轉換就足夠了:

xx[ii] = 12345 * ( (uint64)xx[i0] + xx[ii] ) % 2147483647;

重要的是要在加法運算之前進行轉換,以防止數值溢出,而不是在運算發生之后進行轉換。

是的,您的初始代碼可以這樣寫:

uint32 t1 = xx[i0] + xx[ii]; // problem is here, result of sum is truncated as it is 32 bit
uint64 t2 = (uint64)t1;
uint64 t3 = 12345 * t2 % 2147483647;
xx[ii] = (uint32)t3;

如果您使用第二種變體,則將具有:

uint64 t0 = (uint64)xx[i0];
uint64 t1 = (uint64)xx[ii];
uint64 t2 = t0 + t1; // no truncation, as the result is 64 bit
uint64 t3 = 12345 * t2 % 2147483647;
xx[ii] = (uint32)t3;

暫無
暫無

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

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