Anyone for a challenge? I am looking for an efficient algorithm to achieve a wrap/overflow behavior for a number fixed with max value.
Say, the max possible number value is defined as:
#define MAX_NUMBER_VALUE 100
And a function translate
that takes a signed 32-bit or 64-bit integer value and "wraps it around" using that MAX_NUMBER_VALUE constant:
int_fast8_t translate(int_fast32_t value) {
if (abs(value) > MAX_NUMBER_VALUE) {
return ...; // This!
}
return value;
}
The expected input and output:
translate(55) => 55
translate(100) => 100
translate(101) => -100
translate(102) => -99
translate(200) => -1
translate(202) => 1
translate(300) => 99
translate(-40) => -40
translate(-100) => -100
translate(-101) => 100
translate(-102) => 99
translate(-200) => 1
translate(-201) => 0
...
The value "walks" around the number as if it was a round planet. This does look similar to how C/C++ handles int overflow conditions. I wonder if there is a fast and efficient way to achieve this kind of wrapping? Like with bit shifting or other bitwise operations?