[英]Is there a way to store lower 64 bits of multiplication int64_t * int64_t in C?
This is the function I need to implement using C.这是我需要使用 C 实现的 function。 Note that it is not allowed to use gcc builtins.
请注意,不允许使用 gcc 内置函数。 Thank you for any help!
感谢您的任何帮助!
''' '''
imull(int64_t a, int64_t b, int64_t *res) {
// a * b = ..32bits..|..32bits..
// *res
*res = a * b;
}
''' '''
When an int64_t
is multiplied by an int64_t
, the true arithmetic result is a 128-bit number with its sign bit at bit 127. The low 64 bits do not contain a sign bit.当
int64_t
乘以int64_t
时,真正的算术结果是一个 128 位数字,其符号位位于第 127 位。低 64 位不包含符号位。 Therefore, the low 64 bits of the multiplication ought to be returned in a uint64_t
, not an int64_t
, and this can be accomplished with:因此,乘法的低 64 位应该在
uint64_t
中返回,而不是在int64_t
中,这可以通过以下方式完成:
imull(int64_t a, int64_t b, uint64_t *res)
{
*res = (uint64_t) a * (uint64_t) b;
}
(The casts avoid overflow in the multiplication, as unsigned integer arithmetic is defined to wrap, not overflow.) (强制转换避免了乘法中的溢出,因为无符号 integer 算术被定义为换行,而不是溢出。)
If the bits must be returned in an int64_t
, this can be done in a way defined by the C standard using:如果必须在
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
is declared in <string.h>
.) (
memcpy
在<string.h>
中声明。)
Also note that if the true arithmetic result fits in an int64_t
, then the int64_t
returned by the above code will equal the true arithmetic result.另请注意,如果真正的算术结果适合
int64_t
,则上述代码返回的int64_t
将等于真正的算术结果。 (This is a property of the two's complement representation, which int64_t
uses.) (这是
int64_t
使用的二进制补码表示的属性。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.