Fix #595 by correctly handling UINT64_MAX and INT_MAX boundaries