Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make artificial underflow/ overflow?

I’d like to clamp calculations in the range of 0-360 in my program. I know if you have an 8-bit integer adding 255 + 1 will overflow to 0 and likewise, 0 – 1 will underflow to 255.
I wrote this function as a test:

//only for negative numbers
function clampTo360 (a) {
  if (a < 0) {
    var b = 361 + a;
    if (b > 0) {
      return b;
    } else {
      clampTo360(b);
    }
  }
}

Is there a better way to code a function so the calculation 0 – 1 will return 360?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can make use of the modulo operator here. However, underflowing inputs will result in negative values.

To avoid that you can add 360 to get a number in the interval [0; 720), and apply the modulo operator again to get a result between 0 and 360:

function clampTo360(g) {
    return (g % 360 + 360) % 360
}
console.log(clampTo360(720))
console.log(clampTo360(360))
console.log(clampTo360(-360))
console.log(clampTo360(-720))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading