C Programming Modulus Operator %

Last modified by Microchip on 2023/11/09 09:06

Applications of the Modulus Operator

1. Truncation: x % 2n where n is the desired word width (e.g. 8 for 8-bits: x % 256)

  • Returns the value of just the lower n-bits of x

2. Can be used to break apart a number in any base into its individual digits

Example

1
2
3
4
5
6
7
8
9
10
 #define MAX_DIGITS 6
long number = 123456;
int i, radix = 10; char digits[MAX_DIGITS];
 
for (i = 0; i < MAX_DIGITS; i++)
 {
   if (number == 0) break;
    digits[i] = (char)(number % radix);
    number /= radix;
 }