Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The result of a modulo operation is negative

Why does the following C code produce negative numbers as output? And how do I prevent this from happening?

    #include <stdio.h>

    int main()
    {
            int i;
            char buf[1024];
            for (i = 0; i < 1024; i++)
                    buf[i] = i%256;

            for (i=0; i<1024; i++) {
                    printf("%d ", buf[i]);
                    if (i%32==31)
                            printf("\n");
            }
    }
like image 490
leonixyz Avatar asked Nov 21 '25 00:11

leonixyz


1 Answers

Let's look at this line of code:

buf[i] = i%256;

Here, i % 256 is computed as a value of type int. However, buf is an array of chars, so when the value is assigned into the array, it's truncated to a char. If the result of the modulus is outside of the range of positive values that can be stored in a char, it may end up wrapping around and being stored as a negative number instead.

In other words, it's not that the modulus produced a negative value as much as you stored the result in a type that can't hold it. Try changing the array to an int array or unsigned char array and see if that fixes things.

Hope this helps!

like image 69
templatetypedef Avatar answered Nov 23 '25 14:11

templatetypedef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!