Mike Cole
Mike Cole

Reputation: 14713

Multiplication issue with Visual Studio debugger for C#

If I enter 174 * 256 * 256 * 256 into the watch window in the C# debugger, the result is
-1375731712. I assume it has something to do with 256, but I'd appreciate a little guidance.

Thanks!!

Upvotes: 3

Views: 348

Answers (6)

Eric Mickelsen
Eric Mickelsen

Reputation: 10377

Nope, nothing to do with 256. It's just the result of that multiplication is larger than the maximum possible signed 32-bit integer, so you got an overflow.

Try this instead:

174L * 256L * 256L * 256L

Those are 64-bit integer literals.

Upvotes: 4

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174309

It's a simple overflow. Try to enter this in your watch window:

(uint)(174 * 256 * 256 * 256)

Upvotes: 0

Mark Sowul
Mark Sowul

Reputation: 10600

You are overflowing the integer. The real answer is 2,919,235,584 but only up to 2,147,483,647 can be represented as a signed integer. Consider an unsigned int (uint), a long, a ulong, or if that isn't big enough. For the watch window you'd probably have to cast the first argument or use a suffix, e.g. 174L * 256L * 256L * 256L

Upvotes: 0

xanatos
xanatos

Reputation: 111860

It does an unchecked overflow (so an overflow withouth error). Think like this: Int32.MaxValue + 1 == Int32.MinValue, but with multiplication.

This explains how an int is represented in memory http://en.wikipedia.org/wiki/Two's_complement

Upvotes: 1

jdehaan
jdehaan

Reputation: 19928

You are facing an integer overflow. You can use the System.Numerics.BigInteger if you want to work with big numbers without limitation (beside the available memory of course). In your special case a long would also do (64 bit integer)

Upvotes: 0

Davide Piras
Davide Piras

Reputation: 44605

Try to enter this:

174 * 256 * 256 * 256f

so result will not get cast to integer but as float.

Upvotes: 0

Related Questions