Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is arithmetic overflow equivalent to modulo operation?

Tags:

I need to do modulo 256 arithmetic in C. So can I simply do

unsigned char i; i++; 

instead of

int i; i=(i+1)%256; 
like image 638
avmohan Avatar asked Feb 06 '14 18:02

avmohan


People also ask

Is modulo arithmetic operator?

The modulo operator, denoted by %, is an arithmetic operator. The modulo division operator produces the remainder of an integer division. produces the remainder when x is divided by y.

Is there any difference between modular arithmetic and Congruences?

(4) n ≡ 0 mod 2 if n is even, and n ≡ 1 mod 2 if n is odd. Modular arithmetic: The key fact about congruences is that congruences to the same modu- lus can be added, multiplied, and taken to a fixed positive integral power. For example, since 6 ≡ −1 mod 7, we have 61000 ≡ (−1)1000 = 1 mod 7.

What is the difference between modular arithmetic and regular arithmetic?

Definition. Modular arithmetic is almost the same as the usual arithmetic of whole numbers. The main difference is that operations involve remainders after division by a specified number (the modulus) rather than the integers themselves.

What happens when arithmetic overflow?

An arithmetic overflow is the result of a calculation that exceeds the memory space designated to hold it. For example, a divide-by-zero yields a much larger result.


1 Answers

No. There is nothing that guarantees that unsigned char has eight bits. Use uint8_t from <stdint.h>, and you'll be perfectly fine. This requires an implementation which supports stdint.h: any C99 compliant compiler does, but older compilers may not provide it.

Note: unsigned arithmetic never overflows, and behaves as "modulo 2^n". Signed arithmetic overflows with undefined behavior.

like image 193
Alexandre C. Avatar answered Oct 22 '22 15:10

Alexandre C.