如何在 C 中对 char 数组应用模运算?

How to apply modulo operation on a char array in C?

已编辑:

我有一个很大的数字,C 本身没有类型。我必须使用一个 char 数组来保存它。例如,我创建了一个 32 字节的数组。它代表一个大数,最大为 2^256。

unsigned char num[32]; // The size could be any number for this question.

我想对其进行modulo运算,比如我想mod大数除以小除数得到整数类型的结果。

int divisor = 1234; // Note that the divisor is much smaller than the big number
int result;

// do something here
// to produce a result
// like result = number mod divisor

我不想使用其他库。我该怎么做?

要执行 mod 一个大数,请使用 mod 一个 unsigned char ( ) 一次。

% 是 C 的 remainder 运算符。对于正操作数,它具有与 mod.

相同的功能
unsigned mod_big(const unsigned char *num, size_t size, unsigned divisor) {
  unsigned rem = 0;
  // Assume num[0] is the most significant
  while (size-- > 0) {
    // Use math done at a width wider than `divisor`
    rem = ((UCHAR_MAX + 1ULL)*rem + *num) % divisor;
    num++;
  }
  return rem;
}