Search code examples
cencryptioncryptographyc89modulo

Modulo (%) in C returning undefined result compared to the same function in Python?


I am writing a (what I thought) was a simple program implementing the affine cipher and have come across an issue in that I am not getting expected results from the modulo in C89.

int main()
{
    foo(10);
    return 0;
}

int foo(int enc)
{
    int a = 5, b = 22, inv_a = 77, result;
    result = (inv_a * (enc - b)) % 128;
    printf("result = %d = %c\n", result, result);
    return result;
}

The result of the above is -28 (undefined behavior?)

Meanwhile, the same function in python:

def foo(enc):
    a = 5
    b = 22
    inv_a = 77
    result = (inv_a * (enc - b)) % 128
    print(result)

foo(10)

returns my expected result of 100. During the debugging process I found the results are the same up to the modulo is used. What is happening in the C modulo I am unaware of?


Solution

  • The % operator in C is does not actually perform modulo, but the remainder of division. The latter allows for negative values.

    Specifically, from section 6.5.5p6 of the C standard:

    the expression (a/b)*b + a%b shall equal a