This can be done with the correct C standard if you have access to the unsigned type, which is the same width as your signed type (i.e. it has one more bit of value), to demonstrate with int64_t :
int64_t mult_wrap_2scomp(int64_t a, int64_t b) { uint64_t result = (uint64_t)a * (uint64_t)b; if (result > INT64_MAX) return (int64_t)(result - INT64_MAX - 1) - INT64_MAX - 1; else return (int64_t)result; }
This does not create problematic intermediate results.
caf Nov 22 '10 at 1:30 2010-11-22 01:30
source share