Skip to content

Instantly share code, notes, and snippets.

@alcides
Created April 10, 2018 09:41
Show Gist options
  • Save alcides/f5c6ff49b6faf3a91c46e92b238c440d to your computer and use it in GitHub Desktop.
Save alcides/f5c6ff49b6faf3a91c46e92b238c440d to your computer and use it in GitHub Desktop.
Explanation of wrap-around in Java
"""
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