Confusing integer overflow happening
Posted: Tue Jan 18, 2022 5:24 pm
Hi folks. I was attempting to build a sound level meter and ran into an issue that I was unable to resolve through googling so far. The rest of the projects code don't matter too much, as the problem appears even when I enter fixed values. Therefore I'm going to skip the setup stuff for the OLED display and other things:
Expected result: 20
Returned result: -2147483648
I assume this is some sort of overflow but I don't quite understand why it would happen, since levelDb is a long. This keeps happening with all values for 30, until the calculation inside the logarithm is >=1, after which it returns the desired results. Could somebody explain to me why this happens and if you're feeling generous, how to fix it?
Many thanks in advance!
Code: Select all
long levelDb = 0;
levelDb = 20 * log(30 / 220) + 60
display.print("Decibel: ");
display.println(levelDb);
Expected result: 20
Returned result: -2147483648
I assume this is some sort of overflow but I don't quite understand why it would happen, since levelDb is a long. This keeps happening with all values for 30, until the calculation inside the logarithm is >=1, after which it returns the desired results. Could somebody explain to me why this happens and if you're feeling generous, how to fix it?
Many thanks in advance!