C ++ overflows prematurely

I had a strange problem with C ++, where a long data type overflowed long before it appeared. What I am doing (with success so far) is for integers to behave like float, so that the range [-32767,32767] maps to [-1.0,1.0]. Where it stumbles, there are larger arguments representing float greater than 1.0:

inline long times(long a, long b) { printf("a=%ld b=%ld ",a,b); a *= b; printf("a*b=%ld ",a); a /= 32767l; printf("a*b/32767=%ld\n",a); return a; } int main(void) { printf("%ld\n",times(98301l,32767l)); } 

What I get as output:

 a=98301 b=32767 a*b=-1073938429 a*b/32767=-32775 -32775 

Thus, the times (98301,32767) are similar to 3.0 * 1.0. This code works fine when arguments at times less than 32767 (1.0), but none of the intermediate steps with the arguments above should overflow 64 bits in length.

Any ideas?

+7
c ++ integer-overflow overflow
source share
4 answers

long is not necessarily 64 bits. try "long long".

+9
source share

The long type is not necessarily 64 bits. If you use a 32-bit architecture (at least on MS Visual C ++), the long type is 32 bits. Check this out with sizeof (long) . There is also a long long data type that can help.

+4
source share

You probably have 32 bit long. Use long long instead.

98301 * 32767 = 3221028867, while 32-bit overflows at 2147483648

+2
source share

The C standard ensures that long will have at least 32 bits (which is actually the case on most 32-bit platforms).

If you need 64 bits, use long long . It is guaranteed to hold at least 64 bits.

+2
source share

All Articles