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

╄→尐↘猪︶ㄣ 提交于 2019-12-11 06:25:32

问题


Edited:

I have a big number that C does not have a type for it natively. I have to use a char array to hold it. As an example, I create a 32-byte array. It represents a large number up to 2 ^ 256.

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

I want to apply modulo operation on it, for example, I want to mod the big number by a small divisor and get an integer type result.

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

I do not want to use other library. How can I do it?


回答1:


To perform mod an a large number, use mod one unsigned char (@Bathsheba) at a time.

% is C's remainder operator. For positive operands it has the same functionality as 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;
}


来源:https://stackoverflow.com/questions/38571700/how-to-apply-modulo-operation-on-a-char-array-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!