consider the following code :
ushort a = 60000;
a = (ushort)(a * a / a);
Console.WriteLine("A = " + a);
//This prints 53954. Why??
and
ushort a = 40000;
a = (ushort)(a * a / a);
Console.WriteLine("a = " + a.ToString());
//This prints 40000. how??
any help appreciable …
Because 60000^2 is 3600000000 but the biggest number an int can hold is 2,147,483,647, so it starts over from -2,147,483,648.
A ushort can hold 65,535 and then starts over from 0:
For instance, this prints 0:
It’s easier to see this if you break it into steps:
That actually exceeds the capacity of an int32, so it starts from -2,147,483,648 thus
bequals -694967296Then when you split B/A you get: -11582 which, when cast into a ushort becomes 53954.
The reason that 40000 works is that it does not exceed the capacity of an int32.
uintcan hold 60000^2 though, so this works:The reason that casting C to ushort yeilds 53954 is because the bytes of C is:
And the bytes of D is:
So they hold the same backing bytes, that’s why you get 53954 and -11582