2

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?

9
  • 3
    Said like this, it has little sense. What do you expect in result? Commented Jul 25, 2016 at 15:25
  • and there are many ways...do you want to know how to convert a string to an integer? Commented Jul 25, 2016 at 15:26
  • 2
    I suspect this is a question about implementing the % operation in arbitrary-precision arithmetic without using a library meant for that purpose Commented Jul 25, 2016 at 15:26
  • I want to treat the char array as a big number and apply modulo. Commented Jul 25, 2016 at 15:27
  • 3
    Your first job: use unsigned char instead. char could be signed 1's complement. That will completely mess things up. Commented Jul 25, 2016 at 15:30

1 Answer 1

5

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Useful answer to an interesting question, if you ask me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.