that’s my code:
long base2(int number)
{
long result = 0;
int num = number;
int multi = 1;
int rem;
while(num > 0)
{
rem = num % 2;
result = result + (rem * multi);
num = num / 2;
multi = multi * 10;
}
return result;
}
I’m getting a weird print: -1884801888
I ran the debugger and its calculating properly but just at the end the final answer changes to this -1884801888
[The printing happens in the main, I checked, the number changes here to -1884801888]
Thank you!
On most common platforms nowadays, both
intandlongare 32 bits wide. You are causing an integer overflow, where the values you’re computing exceed the range representable in signed 32-bit integers.If the values don’t fit in 32 bits but do fit in 63 or 64 bits, you can use
long longorunsigned long long(or the fixed-width typesint64_toruint64_tfrom<stdint.h>) data types to store the result. If those aren’t big enough, then you’ll need to use a more complicated solution (e.g. the GMP library has arbitrary-sized integer support), but only do that as a last resort.