问题
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