Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

1000000000 * 3 = -1294967296?

I'm confused!

Today is November 3rd

DateTime DateTime = new DateTime(2010,11,3);
long shazbot = 1000000000 * DateTime.Day;

shazbot comes out to -1294967296

Huh???

like image 439
sooprise Avatar asked Nov 03 '10 14:11

sooprise


2 Answers

shazbot may be a long, but neither 1000000000 or DateTime.Day are. So, C# does int multiplication first (which results in an overflow) then casts it to a long to store in shazbot.

If you want a long result, make one of them a long, like this:

long shazbot = 1000000000L * DateTime.Day;

Edit: C# gives you a warning if you use l instead of L. Fixed.

like image 161
Powerlord Avatar answered Sep 29 '22 03:09

Powerlord


Cast to long like this:

long shazbot = 1000000000L * DateTime.Day;
like image 28
Jeff LaFay Avatar answered Sep 29 '22 01:09

Jeff LaFay