Saranya Subramanian
Saranya Subramanian

Reputation: 461

Casting Double to Int

I found an example for casting. When I try to cast long to int, I get the following output.

long e = 10;
int x = (int) e ;
WriteLine($"e is {e:N0} and x is {x:N0} ");
e = long.MaxValue;
x = (int) e;
WriteLine($"e is {e:N0} and x is {x:N0} ");
e = 5_000_000_000;
x = (int) e;
WriteLine($"e is {e:N0} and x is {x:N0} ");

For case 1, 10 can fit into int, so there is no issue,
For case 2, value -> long max value won't fit in int, so the output is 1
For case 3, value = 5_000_000_000, which also won't fit in int, so it should output 1, but it outputs 705,032,704 Can anyone explain why we are getting this value?

Output of above code is :

e is 10 and x is 10 

e is 9,223,372,036,854,775,807 and x is -1

e is 5,000,000,000 and x is 705,032,704

Upvotes: 1

Views: 153

Answers (2)

Rich N
Rich N

Reputation: 9475

The reason is that under the covers we're working in binary, and when we cast to a smaller binary value we take as many binary bits as we can from the old value to create our new value.

5,000,000,000 in binary is 100101010000001011111001000000000. If we put this in 32 bits (the size of an int) we get 00101010000001011111001000000000. We just lose the leading 1 because the original number is 33 bits. If we convert that to decimal it is 705032704.

This converter is useful to see this.

Edit:

For long.MaxValue becoming -1 we have to understand how we represent negative numbers in binary. We use the leftmost bit. If it's zero the number is positive, if it's one the number is negative. So for a 64-bit number the maximum positive value is 0 plus 63 1's: 0111111111111111111111111111111111111111111111111111111111111111. If we have 64 1's the number is negative, in fact it's -1 by the way negative numbers work, and obviously that isn't the maximum possible value.

Now if we take the rightmost 32 bits of that big binary number we get 32 1's in a row, and that is -1. The BBC has quite a good explanation of negative number representations in binary.

Upvotes: 5

Max
Max

Reputation: 1902

You need to look at (int)e operation like (e % int.MaxValue), so in your example you get the following:

long.MaxValue % int.MaxValue = 1

5000000000 % int.MaxValue = 705032704

Upvotes: 0

Related Questions