Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何在模运算之前键入uint32数组的强制转换元素?_C_Arrays_Casting_Modulo - Fatal编程技术网

C 如何在模运算之前键入uint32数组的强制转换元素?

C 如何在模运算之前键入uint32数组的强制转换元素?,c,arrays,casting,modulo,C,Arrays,Casting,Modulo,我被迫将输出存储在无符号整数数组中。然而,输出是对模2147483647(即模2^31-1)的阵列中先前元素的线性组合的解 下面是一个较大函数的代码片段。很快,当ii环绕xx索引时,这个片段将产生错误的答案。请注意,xx是在调用函数之前播种的,因此数组中的任何元素都不是空的 #include <stdint.h> typedef unsigned int uint32; typedef unit_least64_t uint64; static uint32 xx[47]; ...

我被迫将输出存储在无符号整数数组中。然而,输出是对模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

也许这是显而易见的,但为什么必须对unit64执行两个类型转换而不是一个呢

只要你把它放在正确的位置,一个类型的cast就足够了:

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;
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;