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

Luk*_*uke 2 c math modulo

编辑:

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

unsigned char num[32]; // The size could be any number for this question.
Run Code Online (Sandbox Code Playgroud)

我想对其进行模运算,例如,我想用一个小除数对大数进行模运算并得到一个整数类型的结果。

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
Run Code Online (Sandbox Code Playgroud)

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

chu*_*ica 5

要执行大量mod ,请使用mod 1 unsigned char( @Bathsheba ,请一次

%是C的余数运算符。对于正操作数,它具有与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;
}
Run Code Online (Sandbox Code Playgroud)