Created
April 10, 2018 09:41
-
-
Save alcides/f5c6ff49b6faf3a91c46e92b238c440d to your computer and use it in GitHub Desktop.
Explanation of wrap-around in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Doc: | |
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.2 | |
If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. | |
""" | |
ma = 7 | |
mi = -8 | |
def wrap(x): | |
slots = ma - mi + 1 | |
while x > ma or x < mi: | |
if x > ma: | |
x -= slots | |
if x < mi: | |
x += slots | |
return x | |
print(wrap(mi-1)) | |
print(wrap(ma+1)) | |
print(wrap(mi)) | |
print(wrap(-mi)) | |
print(wrap(-wrap(-mi))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment