문제

i don't understand the modulo operation in the following paragraph:---

when overflow occurs during an operation on unsigned integers,though,the result is defined :we get the correct answer modulo 2^n , where n is the number of bits used to store the result.for example, if we add 1 to the unsigned 16-bit number 65,535 , the result is guaranteed to be 0.

도움이 되었습니까?

해결책

Imagine a clock that has values with a range [0..11] (12 distinct values), when you say the time is 14:00 you can also say it is 2pm, which is 14 mod 12. The same happens when an integer overflows (65,536 mod 65,536 is 0). Whether the answer is semantically correct in your application depends on the application.

다른 팁

With n-bits you can represent a range of numbers from 0 to 2^n-1. So, if you add a number and the result is greater than 2^n-1 it couldn't be represented as it.

imagine you can only represent 5 numbers:

0 1 2 3 4

then, 2+3=5 couldn't be represented, but 5 mod 5 = 0 can be represented

0 1 2 3 4 0 1 2 3 4 5

This is because 2^n-1 is the binary: 1111 1111 .... 1111 (n times) and if you add a number to it, you'll have an overflow and the count starts again:

1111 + 0001= 0000

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top