Skip to content

Instantly share code, notes, and snippets.

@basilevs
Created December 29, 2012 15:55
Show Gist options
  • Select an option

  • Save basilevs/4407717 to your computer and use it in GitHub Desktop.

Select an option

Save basilevs/4407717 to your computer and use it in GitHub Desktop.
#include <limits>
#include <assert.h>
template<class T>
long compensateOverflow(long near, T value)
{
using namespace std;
static const long delta = long(numeric_limits<T>::max()) - numeric_limits<T>::min() + 1;
assert(delta%2 == 0);
assert(delta > 10);
assert(value < delta);
assert(value > -delta);
long rv = near - near % delta + value ;
if (rv < near - delta / 2 )
rv += delta;
else if (rv > near + delta / 2)
rv -= delta;
assert(abs(rv - near) < delta / 2);
return rv;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment