简体   繁体   中英

Integer overflow in C++ even when using `unsigned long`

I'm trying to use C++ to calculate a number for me, but I got a wrong answer. I think it might to do with the data type?

I tried to convert all numbers to unsigned long before multiplying, but the result is the same.


#include <iostream>
using namespace std;

   int main()
   {
    unsigned int width = 8864;
    unsigned int height = 5288;
    unsigned int NImg = 50;
    unsigned long TotalBytes;

    TotalBytes = (width * height * NImg + 2 ) * 2;

    cout<<TotalBytes<<endl;

    }

TotalBytes should be calculated as 4687283204, but the c++ code gives me 392315908.

Thank you very much

On your platform unsigned long is also 32 bits, just like unsigned int . That's not big enough to store the result of the calculation. You'll have to use unsigned long long , or if you'd prefer, you could use uint64_t :

#include <iostream>
#include <cstdint>
using namespace std;

int main()
{
    uint64_t width = 8864;
    uint64_t height = 5288;
    uint64_t NImg = 50;
    uint64_t TotalBytes;

    TotalBytes = (width * height * NImg + 2 ) * 2;

    cout<<TotalBytes<<endl;

}

Try to use Big Integer. You can create a class or use someone's library to implement it. For example, http://www.cplusplus.com/forum/general/108176/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM