简体   繁体   中英

Unsigned long long wrong given value after add

I have two strings to add. Strings is HEX values. I convert strings to long long, add and after I back to string. But this operation no working good.

Code:

unsigned long long FirstNum = std::strtoull(FirstString.c_str(), NULL, 16);
unsigned long long SecondNum = std::strtoull(SecondString.c_str(), NULL, 16);
unsigned long long Num = FirstNum + SecondNum;
std::cout << "  " << FirstNum << "\n+ " << SecondNum << "\n= " << Num << "\n\n";

I received

  13285923899203179534
+ 8063907133566997305
= 2903086959060625223

Anyone can explain me this magic? How can I fix it?

Back to hex value by

std::stringstream Stream;
Stream << std::hex << Num;
return Stream.str();

All unsigned arithmetic in C (and C++) occurs modulo 2 k for some k. In your case, you are getting the result modulo 2 64 , implying that unsigned long long is 64 bits on your platform.

If you want to do arithmetic with integers larger than the largest supported type on your platform, you'll need to use a multiprecision library such as GMP

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