如何在C中的char数组上应用模运算? [英] How to apply modulo operation on a char array in C?

查看:80
本文介绍了如何在C中的char数组上应用模运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

要大量执行 mod ,请使用 mod 一个unsigned char(@Bathsheba ) .

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

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

% 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;
}

这篇关于如何在C中的char数组上应用模运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆