0

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();
4

1 回答 1

2

C(和 C++)中的所有无符号算术对于某些 k都以 2 k为模。在您的情况下,您将得到模 2 64的结果,这意味着 unsigned long long 在您的平台上是 64 位。

如果您想使用大于平台上支持的最大类型的整数进行算术运算,则需要使用多精度库,例如GMP

于 2015-11-25T18:51:47.233 回答