gpt4 book ai didi

c - 如何在c中计算数组元素与整数的模乘?

转载 作者:行者123 更新时间:2023-11-30 18:44:59 25 4
gpt4 key购买 nike

考虑以下因素:

uint8_t message[15] = {
0x32, 0xdc, 0x21, 0x55, 0x3f, 0x87, 0xc8, 0x1e,
0x85, 0x10, 0x43, 0xf9, 0x93, 0x34, 0x1a
};
uint64_t num = 0xa1b2c33412;

我想将上面的变量 num 乘以数组 message[]。我需要的伪代码如下:

uint8_t message[15] = {
0x32, 0xdc, 0x21, 0x55, 0x3f, 0x87, 0xc8, 0x1e,
0x85, 0x10, 0x43, 0xf9, 0x93, 0x34, 0x1a
};
uint64_t num = 0xa1b2c33412;
uint64_t p = 0x31ba62ca3037;
uint64_t result = 0x00;
result = moduloMultiplication(message, num, p); // (message * num) (mod p)

我期待以下结果:

num * msg = num*msg mod p
num * msg = 0x2bf2d18cdf92 (Final result)

有没有办法将数组与uint64_t类型的值相乘?

任何有关此问题的帮助将不胜感激......

最佳答案

假设 15 字节数组中存储的数字是大端顺序,这里有一个简单的解决方案:

#include <stdio.h>
#include <stdint.h>

uint64_t moduloMultiplication(const uint8_t message[15], size_t n,
uint64_t num, uint64_t p)
{
uint64_t res = 0;
for (size_t i = 0; i < n; i++) {
// assuming `p < 1ULL << 56`
res = (res * 256 + message[i] * num) % p;
}
return res;
}

int main() {
uint8_t message[15] = {
0x32, 0xdc, 0x21, 0x55, 0x3f, 0x87, 0xc8, 0x1e,
0x85, 0x10, 0x43, 0xf9, 0x93, 0x34, 0x1a
};
uint64_t num = 0xa1b2c33412;
uint64_t p = 0x31ba62ca3037;
// result = (message * num) (mod p)
uint64_t result = moduloMultiplication(message, sizeof message, num, p);

printf("%#"PRIx64"\n", result);
return 0;
}

输出:0x2bf2d18cdf92

结果与问题中的结果不同,因为消息不正确,或者您的中间结果是近似的:201FF4CDCFE8C0000000000000000000000000000似乎不正确。

关于c - 如何在c中计算数组元素与整数的模乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55991997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com