简体   繁体   English

C++ 两个无符号长整数相乘的错误结果

[英]C++ wrong result in multiplication of two unsigned long long integers

Consider the multiplication of the following unsigned long long integers:考虑以下unsigned long long整数的乘法:

unsigned long long a=4294967297;
unsigned long long b=4294967297;
cout<<a*b<<endl;

8589934593 8589934593

I did not expect this answer.我没想到这个答案。 Instead I was expecting to get:相反,我期待得到:

18446744065119617025 18446744065119617025

Note that, according to this source , the largest integer that can be represented by an unsigned long long is 18446744073709551615 (or in hexadecimal 0xffffffffffffffff ).请注意,根据此来源,可以用unsigned long long表示的最大 integer 是18446744073709551615 (或十六进制的0xffffffffffffffff )。 This is by 8589934590 larger than my expected 18446744065119617025 , so that I was assuming this number could still be represented.这比我预期的8589934590大了18446744065119617025 ,所以我假设这个数字仍然可以表示。

What is going on and how to resolve this issue?发生了什么事以及如何解决这个问题?

EDIT:编辑:

You guys are right, I was playing around with different numbers and confused the results of 4294967297 and 4294967295 squared.你们是对的,我在玩不同的数字,混淆了42949672974294967295的平方结果。 With 7 at the end it does overflow.最后是7它会溢出。 Thanks for pointing this out.感谢您指出了这一点。

I think you're doing your math wrong:我认为你做错了数学:

slowpy3.8> 4294967297 * 4294967297
18446744082299486209
slowpy3.8> hex(_)
'0x10000000200000001'
slowpy3.8> 0xffffffffffffffff > 0x10000000200000001
False
slowpy3.8> math.log2(18446744082299486209)
64.0000000006718
slowpy3.8> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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